日期值延迟一天的原因是什么?

时间:2016-01-21 11:19:55

标签: ios objective-c nsdateformatter nstimezone

下面是我的示例代码。

NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate * dateFormatted = [dateFormatter dateFromString:@"2016-01-17"];
NSLog(@"Date : %d",dateFormatted);

输出为2016-01-16 18:30:00 +0000。如何获取日期格式2016-01-17。延迟一天的原因是什么?请帮帮我。

3 个答案:

答案 0 :(得分:2)

您不应该在没有时区标记的情况下从NSString创建NSDate。

  1. 将时区添加到NSString like "-0800"

    e.g. "2016-01-17 -0800"  --> "yyyy-MM-dd Z"
    
  2. 添加代码:

    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];// change timezone u want
    

答案 1 :(得分:1)

   NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate * dateFormatted = [dateFormatter dateFromString:@"2016-01-17"];
    NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
    NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:dateFormatted];
    NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];

    NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:dateFormatted];

    NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset;
    NSDate *destinationDate = [[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:dateFormatted] ;

    NSLog(@"Date : %@",destinationDate);

答案 2 :(得分:0)

您可以使用以下代码......!

我在前两个场景中强迫日期为2016-01-17。你可以检查和使用它是否对你有用..!

    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate * sourceDate = [dateFormatter dateFromString:@"2016-01-17"];

    int daysToAdd = 1;
    NSDate *presentDate = [sourceDate dateByAddingTimeInterval:60*60*24*daysToAdd]; //Output 2016-01-17 18:30:00 +0000

    NSDate * dateFormatted = [dateFormatter dateFromString:@"2016-01-17"];
    NSCalendar *calendar1 = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components1 = [calendar1 components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:dateFormatted];
    [components1 setHour:24];//24
    [components1 setMinute:00];//00
    NSDate *presentDate1 = [calendar1 dateFromComponents:components1]; //Output 2016-01-17 18:30:00 +0000

    //The input
    NSString *myDateAsAStringValue = @"2016-01-17";

    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    [df setDateFormat:@"yyyy-MM-dd"];

    //Getting Date
    NSDate *myDate = [df dateFromString: myDateAsAStringValue]; // Output 2016-01-17 00:00:00 +0000

    //create the formatter for the output
    NSDateFormatter *out_df = [[NSDateFormatter alloc] init];
    [out_df setDateFormat:@"yyyy-MM-dd"];

    NSString *dateStr=[out_df stringFromDate:myDate];//2016-01-17

希望它可以帮助你......!