Swift: NSDate formatting with strftime & localtime

2020-02-10 05:38发布

How do I convert the following Objective-C code into Swift code?

#define MAX_SIZE 11
char buffer[MAX_SIZE];
time_t time = [[NSDate date] timeIntervalSince1970];
strftime(buffer, MAX_SIZE, "%-l:%M\u2008%p", localtime(&time));
NSString *dateString = [NSString stringWithUTF8String:buffer];
NSLog(@"dateString: %@", dateString); // dateString: 11:56 PM

I'm formatting a date.

4条回答
不美不萌又怎样
2楼-- · 2020-02-10 06:24

My function i use.

extension NSDate {
    public func toString (format: String) -> String {
        let formatter = NSDateFormatter ()
        formatter.locale = NSLocale.currentLocale()
        formatter.dateFormat = format

        return formatter.stringFromDate(self)
    }
}
date.toString("yyyy-MM-dd")
查看更多
祖国的老花朵
3楼-- · 2020-02-10 06:32

As the commentators @BryanChen and @JasonCoco said, use NSDateFormatter.

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd 'at' h:mm a" // superset of OP's format
let str = dateFormatter.stringFromDate(NSDate())

A full description of the format strings is available in "Data Formatting Guide".

查看更多
爷的心禁止访问
4楼-- · 2020-02-10 06:32
    let maxSize: UInt = 11
    var buffer: CChar[] = CChar[](count: Int(maxSize), repeatedValue: 0)
    var time: time_t = Int(NSDate().timeIntervalSince1970)
    var length = strftime(&buffer, maxSize, "%-l:%M\u2008%p", localtime(&time))
    var dateString = NSString(bytes: buffer, length: Int(length), encoding: NSUTF8StringEncoding)
    NSLog("dateString: %@", dateString) // dateString: 11:56 PM
查看更多
时光不老,我们不散
5楼-- · 2020-02-10 06:34

Here is another example that uses NSDateFormatterStyle:

private func FormatDate(date:NSDate) -> String {
  let dateFormatter = NSDateFormatter()
  dateFormatter.dateStyle = NSDateFormatterStyle.LongStyle
  return dateFormatter.stringFromDate(date)
}

The output is formatted as, "January 1, 1990".

If you want to read more about the formatter and the different available styles, checkout, NSFormatter under NSDateFormatter section.

查看更多
登录 后发表回答