Assign [NSDate date] to NSString in Swift

In Objective-C, we can easily set the current date to an NSString, for example string = [NSDate date]; .

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

+5
source share
2 answers

First of all, your expression ...

In Objective-C, we could easily set the current date to an NSString, for example string = [NSDate date];

This is complete trash.

In Objective-C, you need to use NSDateFormatter to output an NSString from an NSDate .

You would do something like this ...

 NSDate *date = [NSDate date]; NSDateFormatter *df = [[NSDateFormatter alloc] init]; df.dateStyle = NSDateFormatterMediumStyle NSString *string = [df stringFromDate:date]; 

Now, in Swift, it is not surprising that this is EXACTLY the same.

 let date = NSDate() let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = .MediumStyle let string = dateFormatter.stringFromDate(date) 
+17
source

maybe you want this:

 let string = NSDate().description 
+11
source

Source: https://habr.com/ru/post/1206236/


All Articles