dateFromComponents的意外结果:

编程入门 行业动态 更新时间:2024-10-26 23:30:17
本文介绍了dateFromComponents的意外结果:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

以下代码

NSCalendar *cal = [NSCalendar currentCalendar]; [cal setFirstWeekday:2]; [cal setMinimumDaysInFirstWeek:4]; NSDateComponents *comp = [[NSDateComponents alloc] init]; [comp setYear: 2012]; [comp setMonth:3]; [comp setDay: 12]; NSDate *date = [cal dateFromComponents:comp]; NSLog(@"date:%@",date);

日志:

date:2012-03-11 23:00:00 +0000

任何想法,为什么会发生这种情况以及如何避免 Tnx

Any Idea, why this happen and how to avoid Tnx

推荐答案

我假设您在本地使用CET时区。这就是 [NSCalendar currentCalendar] 将用作时区。

I assume you are using the CET time zone locally. This is what the [NSCalendar currentCalendar] will use as a time zone then.

当您转储 NSDate 使用NSLog,您将以原始UTC格式获取日期。要使用本地格式打印日期,请查看 NSDateFormatter 类,该类具有 timeZone 属性:

When you dump a NSDate with NSLog, you will get the date in its raw UTC form. To print the date using a local format, look into the NSDateFormatter class, which has a timeZone property:

.... NSDate *date = [cal dateFromComponents:comp]; NSDateFormatter* fmt = [[NSDateFormatter alloc] init]; fmt.timeZone = [NSTimeZone defaultTimeZone]; // Probably not required NSLog(@"date:%@", [fmt stringFromDate:date]);

更多推荐

dateFromComponents的意外结果:

本文发布于:2023-11-13 14:12:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1584533.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:意外   dateFromComponents

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!