Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning [NSDate date] to NSString in Swift

In Objective C, we could easily assign present date to NSString like string = [NSDate date];.

Could someone help me how to assign the same in Swift ? Thanks in advance.

like image 750
Riyazul Aboobucker Avatar asked Nov 05 '14 10:11

Riyazul Aboobucker


2 Answers

First off, your statement...

In Objective C, we could easily assign present date to NSString like string = [NSDate date];

Is complete rubbish.

In Objective-C you need to use an NSDateFormatter to render an NSString out of an NSDate.

You would do it something like this...

NSDate *date = [NSDate date];

NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle

NSString *string = [df stringFromDate:date];

Now, in Swift, not surprisingly, it is EXACTLY the same.

let date = NSDate()

let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle

let string = dateFormatter.stringFromDate(date)
like image 137
Fogmeister Avatar answered Oct 10 '22 10:10

Fogmeister


maybe you want this:

let string = NSDate().description
like image 27
ChikabuZ Avatar answered Oct 10 '22 10:10

ChikabuZ