使用 NSDateFormatter 从 NSString 格式化日期

发布于 2025-01-02 09:57:30 字数 722 浏览 4 评论 0原文

我有以下代表日期和日期的字符串时间

NSString *shortDateString = @"Sat28Apr2012 15:00";

(没有空格(除了时间前面的一个空格),就像上面一样)

我想使用以下方法格式化该日期:

NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
// Question is regarding the line below:
[inputFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm"];

NSDate *formatterDate = [inputFormatter dateFromString:shortDateString];

NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[outputFormatter setTimeZone:gmt];
[outputFormatter setDateFormat:@"dd.MMM.yyyy HH:mm Z"];

NSString *newDateString = [outputFormatter stringFromDate:formatterDate];

I have the following string representing a date & time

NSString *shortDateString = @"Sat28Apr2012 15:00";

(no spaces (apart from a single space in front of the time), just as it is above)

I would like to format this date using:

NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
// Question is regarding the line below:
[inputFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm"];

NSDate *formatterDate = [inputFormatter dateFromString:shortDateString];

NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[outputFormatter setTimeZone:gmt];
[outputFormatter setDateFormat:@"dd.MMM.yyyy HH:mm Z"];

NSString *newDateString = [outputFormatter stringFromDate:formatterDate];

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

等风也等你 2025-01-09 09:57:30

如果您稍微更改字符串以完全匹配输入的格式,它就可以正常工作。您需要做的就是从字符串中删除空格和逗号,如下所示:

"EEEdMMMyyyy HH:mm"

使用此字符串,我得到以下结果:

08.Apr.2012 19:00 +0000

It is 19:00, not 15:00,因为我的时区比 GMT 晚四个小时。

If you change your string slightly to match the format of your input exactly, it works fine. All you need to do is removing spaces and the comma from the string, like this:

"EEEdMMMyyyy HH:mm"

With this string I get the result below:

08.Apr.2012 19:00 +0000

It is 19:00, not 15:00, because my time zone is four hours behind GMT.

咋地 2025-01-09 09:57:30
[inputFormatter setDateFormat:@"EEEddMMMyyyy HH:mm"];
[inputFormatter setDateFormat:@"EEEddMMMyyyy HH:mm"];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文