将 NSDate 格式化为年、月、日和时、分、秒的特定样式 [英] Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

查看:48
本文介绍了将 NSDate 格式化为年、月、日和时、分、秒的特定样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<前>2009-04-2611:06:54

下面的代码来自同一主题的另一个问题,生成

<前>现在:|2009-06-01 23:18:23 +0100|日期字符串:|2009 年 6 月 1 日 23:18|解析:|2009-06-01 23:18:00 +0100|

这几乎就是我要找的,但我想把日子和时间分开.

NSDateFormatter *format = [[NSDateFormatter alloc] init];[格式 setDateFormat:@"MMM dd, yyyy HH:mm"];NSDate *now = [[NSDate alloc] init];NSString *dateString = [格式 stringFromDate:now];NSDateFormatter *inFormat = [[NSDateFormatter alloc] init];[inFormat setDateFormat:@"MMM dd, yyyy"];NSDate *parsed = [inFormat dateFromString:dateString];NSLog(@"
"现在:|%@| 
""日期字符串:|%@| 
"已解析:|%@|",现在,日期字符串,已解析);

解决方案

iPhone 格式字符串位于 Unicode 格式.链接后面是一张表格,解释了上述所有字母的含义,因此您可以构建自己的.

当然,不要忘记在完成日期格式化程序后发布它们.上面的代码泄露了formatnowinFormat.

I basically need to get current date and time separately, formatted as:

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(@"
"
"now:        |%@| 
"
"dateString: |%@| 
"
"parsed:     |%@|", now, dateString, parsed);

解决方案

iPhone format strings are in Unicode format. Behind the link is a table explaining what all the letters above mean so you can build your own.

And of course don't forget to release your date formatters when you're done with them. The above code leaks format, now, and inFormat.

这篇关于将 NSDate 格式化为年、月、日和时、分、秒的特定样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆