我想以UTC格式转换本地日期。(美国格式)
答案 0 :(得分:22)
-(NSString *)getUTCFormateDate:(NSDate *)localDate
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate:localDate];
[dateFormatter release];
return dateString;
}
答案 1 :(得分:6)
您应该设置NSTimeZone
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSDate *date=[dateFormat dateFromString:[NSString stringWithFormat:@"%@",dateString]];
NSLog(@"Date %@",date);
答案 2 :(得分:0)
Swift 4.2版本:
func dateAsString(inputDate: Date)->String
{
let format = DateFormatter.init()
format.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
format.timeZone = TimeZone.init(identifier: "UTC")
let str = format.string(from: inputDate)
return str
}