简体   繁体   中英

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.

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)

也许你想要这个:

let string = NSDate().description

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM