本文介绍了NsDate格式化程序从String给出错误的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码,它接受NSString并返回NSDate。我已经从一个完全正常运行的项目中复制了这个代码 - 但是有些如何给我错误的输出
I have the following code which takes a NSString and returns NSDate. I have copied this code from a project in which it runs perfectly fine - but some how this gives me the wrong output
- (NSDate *)dateFromString:(NSString *)date
{
static NSDateFormatter *dateFormatter;
if (!dateFormatter)
{
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
}
NSLog(@"Date: %@ Formatted: %@",date,[dateFormatter dateFromString:date]);
return [dateFormatter dateFromString:date];
}
,输出来自日志:
Date: 07-01-2014 Formatted: 2014-01-06 18:30:00 +0000
Date: 24-01-2014 Formatted: 2014-01-23 18:30:00 +0000
Date: 06-01-2014 Formatted: 2014-01-05 18:30:00 +0000
Date: 15-01-2014 Formatted: 2014-01-14 18:30:00 +0000
Date: 22-01-2014 Formatted: 2014-01-21 18:30:00 +0000
Date: 31-01-2014 Formatted: 2014-01-30 18:30:00 +0000
Date: 14-01-2014 Formatted: 2014-01-13 18:30:00 +0000
Date: 30-01-2014 Formatted: 2014-01-29 18:30:00 +0000
奇怪的是,它也改变了日期.. !!
任何帮助...... !!!
In a weird sense it is also changing the Date..!!Any help...!!!
推荐答案
结果是格林威治标准时间输出结果 - 即如果你距格林威治标准时间5:3小时。
The results are formated for GMT output - i.e. if you are 5:3 hours away from GMT.
如果您希望在该时区内返回格式化日期,则需要指定时区:(即+ 00表示的含义)
You need to specify a timezone if you want the date formated to be returned in that timezone: (that is what the +0000 means)
- (NSDate *)dateFromString:(NSString *)date
{
static NSDateFormatter *dateFormatter;
if (!dateFormatter)
{
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
}
NSLog(@"Date: %@ Formatted: %@",date,[dateFormatter dateFromString:date]);
return [dateFormatter dateFromString:date];
}
这篇关于NsDate格式化程序从String给出错误的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!