简体   繁体   English

将NSString转换为NSDate,增加时间

[英]Convert NSString to NSDate, adding time

I have an NSString that is 05/08/2014. 我有一个2014年5月8日的NSString。 I want to convert that to an NSDate. 我想将其转换为NSDate。 However, I also need to add in time, so that the resulting NSDate looks like this: 但是,我还需要及时添加,以使生成的NSDate看起来像这样:

Thu, 8 May 2014 00:00:00 -0500

The time is not important, I just need it to show midnight at the designated timezone. 时间并不重要,我只需要显示在指定时区的午夜。

I have tried: 我努力了:

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

        [dateFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss zzz"];
        NSDate *dateFromString = [[NSDate alloc] init];
        dateFromString = [dateFormatter dateFromString:textdate.text];
        [dateFormatter release];
        NSLog(@"%@", dateFromString);

But the date comes back as (null). 但是日期返回为(空)。

Your date format is wrong for the first conversion. 您的日期格式第一次转换错误。 What you need is first to convert from string to date from one format and form the new date into the new string format. 您首先需要从一种格式的字符串转换为日期,然后将新日期转换为新的字符串格式。 Something like this: 像这样:

NSDateFormatter  *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM/dd/yyyy"]; //convert the string into date (american time zone)
    NSDate *theDate = [formatter dateFromString:textdate.text];
    [formatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss ZZZ"];// as @Logan suggested
    NSString *newDate = [formatter stringFromDate:theDate];

EEE, d MMM yyyy HH:mm:ss ZZZ EEE,d MMM yyyy HH:mm:ss ZZZ

Your time zone code was lowercase instead of uppercase. 您的时区代码是小写而不是大写。

zzz corresponds to PDT zzz对应于PDT

ZZZ corresponds to -0500 ZZZ对应-0500

UTS 35 悉尼科技大学35

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

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