cocoa - 将 NSDate 格式化为年、月、日、时、分、秒的特定样式

标签 cocoa cocoa-touch nsdate nsdateformatter date-formatting

我基本上需要分别获取当前日期和时间,格式为:

2009-04-26 
11:06:54

The code below, from another question on the same topic, generates

now:        |2009-06-01 23:18:23 +0100| 
dateString: |Jun 01, 2009 23:18| 
parsed:     |2009-06-01 23:18:00 +0100|

This is almost what I'm looking for, but I want to separate the day and time.

NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"MMM dd, yyyy HH:mm"];

NSDate *now = [[NSDate alloc] init];

NSString *dateString = [format stringFromDate:now];

NSDateFormatter *inFormat = [[NSDateFormatter alloc] init];
[inFormat setDateFormat:@"MMM dd, yyyy"];

NSDate *parsed = [inFormat dateFromString:dateString];

NSLog(@"\n"
"now:        |%@| \n"
"dateString: |%@| \n"
"parsed:     |%@|", now, dateString, parsed);

最佳答案

这是我使用的:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];

NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"HH:mm:ss"];

NSDate *now = [[NSDate alloc] init];

NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];

NSLog(@"\n"
      "theDate: |%@| \n"
      "theTime: |%@| \n"
      , theDate, theTime);

[dateFormat release];
[timeFormat release];
[now release];

关于cocoa - 将 NSDate 格式化为年、月、日、时、分、秒的特定样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/936969/

相关文章:

objective-c - 12 小时模式的 NSDateFormatter

objective-c - 计算两个日期之间的白天时间和夜间时间

ios - 在 iPad 3 上渲染手绘上下文的最佳实践

objective-c - 允许单击并拖动 View 以拖动窗口本身?

objective-c - NSTextView 未将文本绘制到 NSImage 上

objective-c - 在 Cocoa Mac OSX 中设置 FirstResponder 时出现问题

iphone - 推送通知证书P12文件

ios - 仅使用自动布局的 iOS8 Today Extension 的高度会破坏约束

ios - 如何将 NSDate 的秒数设置为零

macos - 设置光标,绕过光标放大率