我有一个日期选择器,只添加该日期的日期我想添加时间字符串并将其转换为日期。
fromString = @"00:00:00";
NSString *fromDate = [fromdate.text stringByAppendingString:@" "];
fromDate = [fromDate fromString];
NSDate *currentDate = [self dateFromString:fromDate withFormat:@"dd/MM/yyyy HH:mm:ss"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/yyyy HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT+5.30"]];
NSString *dateString = [dateFormatter stringFromDate: currentDate];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSDate *date = [self dateFromString: dateString withFormat:@"dd/MM/yyyy HH:mm:ss"];
NSString *fromDate1 = [NSString stringWithFormat:@"/Date(%.0f000%@)/", [date timeIntervalSince1970],[formatter stringFromDate:date]];
我的问题是,在转换为字符串时,我的额外时间增加了5.30。
答案 0 :(得分:0)
我的问题是我在转换为字符串时会增加5.30的额外时间。
要从字符串初始转换,请使用:
NSDate *CurrentDate = [self dateFromString:fROMDATE withFormat:@"dd/MM/yyyy HH:mm:ss"];
您没有提供dateFromString
的代码,但我猜这个例程正在使用GMT / UTC时区进行转换。
要转换回您首先执行的字符串:
[DATEFORMATER setTimeZone:[NSTimeZone timeZoneWithName:@"GMT+5.30"]];
因此,如果您的原始时间是从字符串转换为GMT,则DATE_STRING
将显示5.5小时的时间"之后" (GMT中的同一时间点,仅显示在GMT + 5.30时区内。)
HTH
答案 1 :(得分:-1)
NSString *finalDate = ……
NSDateFormatter *dateFormatterTime = [[NSDateFormatter alloc] init];
NSLocale *location = [NSLocale currentLocale];
NSString *country = [location localeIdentifier];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:country];
[dateFormatterTime setLocale:locale];
[dateFormatterTime setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *timeZone = [dateFormatterTime dateFromString:finalDate];
[dateFormatterTime setDateFormat:@"yyyy-MM-dd hh:mm:ss a"];
NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"EST"]; // set as you wish
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:timeZone];
NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:timeZone];
NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset;
// get final date in LocalTimeZone
NSDate *destinationDate = [[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:timeZone];
NSLog(@“你的NSDate =%@”,destinationDate);