繁体   English   中英

从字符串设置nsdate值时出现问题

[英]Problem in setting nsdate value from a string

    NSDate *My_StartDate,*My_EndDate ;
NSDateFormatter * df= [[NSDateFormatter alloc]init];
[df setDateFormat:@"dd/MM/yyyy hh:mm:ss"];
My_StartDate = [df dateFromString:@"01/05/2010 10:15:33"];
My_EndDate = [df dateFromString:@"01/05/2010 10:45:33"];
NSLog(@"%@",My_StartDate);
NSLog(@"%@",My_EndDate);

在日志中,我将my_startdate设置为2010-05-01 04:45:33 +0000,将结束日期设置为2010-05-01 05:15:33 +0000,这样,我应该具有开始日期的值如2010-05-01 10:15:33 +0000,结束日期如2010-05-01 10:45:33 +0000

尝试以下功能:

-(NSString *)getDateStringFromDate :(NSDate *)dateValue{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];

NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setTimeStyle:NSDateFormatterShortStyle];

[timeFormat setDateFormat:@"HH:mm:ss"];
//[timeFormat setDateFormat:@"HH:mm"];  
//[timeFormat setDateFormat:@"HH:mm a"];    
////    

 NSString *theDate = [dateFormat stringFromDate:dateValue];
 NSString *theTime = [timeFormat stringFromDate:dateValue];

 NSLog(@"\n"          
 "theDate: |%@| \n"
 "theTime: |%@| \n"
 , theDate, theTime);

return theDate;
}

根据需要更改数据格式。

如果有任何困难,请告诉我。

干杯。

它显示为格林尼治标准时间+4.30时间。仅显示为类似日期。当您使用DateFormatter将日期转换为字符串时,它会给出相同的日期(您希望起始日期为01/05/2010 10:15:33和结束日期为01/05/2010 10:45:33)。

NSDateFormatter * dateformatter= [[NSDateFormatter alloc]init];
[dateformatter setDateFormat:@"dd/MM/yyyy hh:mm:ss"];
NSString *dat = [dateformatter stringfromDate:My_StartDate];

那么您将得到的输出为01/05/2010 10:15:33

这显示了遵循美国标准时间字符串的日期,但是因此您在逻辑上没有任何问题。

[df setDateFormat:@"dd/MM/yyyy hh:mm:ss"];

这种格式使用12小时格式(分别表示2:03 pm和2:03 am),日期对象从不使用am和pm显示日期对象的值,但是正确转换日期后,它会为您提供正确的日期和时间。

如果您觉得有任何问题,请为此使用其他语言环境。

您可能需要在此处将日期格式器的时区设置为GMT 使用它

[df setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];

在执行dateFromString:调用之前。 这会给你你想要的。

只需在您的代码中更新:

我可能希望您的时间采用24小时制,所以那时您需要使用....而不是设置时区。

单击所有区域的此链接: http : //unicode.org/reports/tr35/tr35-6.html#Date%5FFormat%5FPatterns

[df setDateFormat:@"dd/MM/yyyy hh:mm:ss"];
to 
[df setDateFormat:@"dd/MM/yyyy HH:mm:ss"];

你做完了;)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM