简体   繁体   English

将(日期+时间)从NSString转换为NSDate并添加一些小时

[英]Convert (Date + Time) from NSString to NSDate and Add Some Hours

Requirement is very simple. 要求很简单。 I have a date+time in 2014-05-16 09:10am format. 我有一个日期+时间2014-05-16 09:10am格式。 I want to convert it in NSDate so that I can add/remove few hours to get a time span for some calculation. 我想在NSDate转换它,以便我可以添加/删除几个小时来获得一些计算的时间跨度。 What exactly dateFormat should I use while converting this NSString value into NSDate ? 在将此NSString值转换为NSDate我应该使用什么NSDate I have tried following 我试过以下

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm a"];
[dateFormatter setDateFormat:@"yyyy-MM-ddTHH:mm a"];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm"];
[dateFormatter setDateFormat:@"yyyy-MM-ddTHH:mm a"];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm ZZZZ"];

I searched on SO but couldn't get the exact answer. 我搜索了SO,但无法得到确切的答案。 I tried mentioned solutions too by molding them according to my requirement but no gain so far. 我也尝试过按照我的要求塑造它们,但到目前为止还没有增加。 So I'm posting my query here. 所以我在这里发布我的查询。

The problem is with your Hours HH - 24 hours format && hh - 12 hours format . 问题在于您的小时数HH - 24小时格式&& hh - 12小时格式。

According to your input date String, This is working fine 根据您输入的日期字符串,这工作正常

 NSString* strdate = @"2014-05-16 09:10am";

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mma"];
    NSDate *date = [dateFormatter dateFromString:strdate];
 NSString* dateString = "2014-05-16 09:10am";
NSDateFormatter* formt = [NSDateFormatter new];
[formt setDateFormat:"yyyy-MM-dd  hh:mma"];   //hh - for 12 hours format
NSDate* date = [formt dateFromString:dateString];

 NSLog(@"your date is ==%@",date);

if u need to add some hours 如果你需要增加几个小时

NSTimeInterval  InEightHours = 8 * 60 * 60;  //mutiple the hours with minutes
NSDate *dateHoursAhead = [date dateByAddingTimeInterval:InEightHours];

NSLog(@"your final date is ==%@", dateHoursAhead);

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

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