NSDate设置为前一天 [英] NSDate being set to the day before
问题描述
重要的更新:你悬停在一个NSDATE与你的鼠标脱机将转换NSDate到你设置在Mac上的本地时区,但如果你做一个NSLOG,你会注意到NSDate正在使用时区,你
Important update: Of you hover over a NSDATE with your mouse the degugger will convert the NSDate to your local timezone you have set on you Mac, but if you do a NSLOG you will notice that the NSDate is using the timezone that you assigned to the its respective formatter.
我需要从传递日期创建一个NSDate,但目前它设置为我传入前一天:
I require a NSDate to be created from the date I pass in, but currently it is set to the the day before I pass in:
NSString *dateStr = @"2015-08-09";
NSDateFormatter *myformatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [formatter dateFromString:dateStr];
上面的代码返回:NSDate设置为'2015-08-08 12:00:00 + 0000'
The code above returns: an NSDate set to '2015-08-08 12:00:00 +0000'
我需要一个NSDate对象设置为我传入的datStr。
I need an NSDate object set to the datStr I pass in.
推荐答案
也许,从这里:
This perhaps, from this:
使用NSDateFormatter将NSDate转换为NSString,使用不包含GMT时间修饰符的TimeZone
'z'小写的命名时区,即PST和大写'Z'-0800
leave the 'z' lowercase for named timezone, i.e. PST and uppercase 'Z' for -0800
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"MMMM dd, yyyy (EEEE) HH:mm:ss z Z"];
NSDate *now = [NSDate date];
NSString *nsstr = [format stringFromDate:now];
此外,您的日期应该更加健壮,如果您想在当天通过正在传入,它是一天了,然后只是添加一天。问题,似乎是日期返回正确的日期,这是最后一天的结束,添加1秒或一毫秒,它可能会得到纠正,或者只是黑客攻击这个,并添加1天的日子是聪明!有时你只需要添加1天来修复和继续。
Also, you date should be more robust, like if you want to pass in the current day that your are passing in and it's one day off, then just add a day. The problem, it seems is that the date is returning the correct date which is the end of the last day, add 1 second or a millisecond and it'll probably be corrected, or just hack attack this and add 1 day to the days you are passing in. Be smart! Sometimes you just have to add 1 day to fix stuff and move on.
这篇关于NSDate设置为前一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!