将时间格式转换为 UTC 格式

Convert time format to UTC format

我正在以这种格式获取时间:

29-Mar-2018 05:58:33

我认为这是 RFC 850 格式。

我需要把这个时间转换成UTC格式

2018-03-29T05:58:33Z

Objective C-

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    //The Z at the end of your string represents Zulu which is UTC
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    [dateFormatter setDateFormat:@"yyyy-dd-MM'T'HH:mm:ss'Z'"];
    NSDate* newTime = [dateFormatter dateFromString:[message valueForKey:@"created_at"]];

    //Add the following line to display the time in the local time zone
    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    [dateFormatter setDateFormat:@"M/d/yy 'at' h:mma"];
    NSString* finalTime = [dateFormatter stringFromDate:newTime];
    [dateFormatter release];
    NSLog(@"%@", finalTime);  

swift-

    extension Date {
    func GetCurrentTimeZoneDate() -> String {
        let abc = DateFormatter()
        abc.timeZone = TimeZone.current
        abc.dateFormat = "yyyy-MM-dd HH:mm:ss"

        return abc.string(from: self)
    }
}

这样称呼:

Date().GetCurrentTimeZoneDate()

我没有输入您需要的确切日期格式

我给你的是如何解决这个问题你必须自己写

1) Create date formatter exact with your current format 
NSDateFormatter *timeFormatter1 = [[NSDateFormatter alloc] init];
[timeFormatter1 setDateFormat:@"yyyy-MM-dd hh:mm a"];
2) set time zone of source time zone
[timeFormatter1 setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
3) Create date object
NSDate *aDate = [timeFormatter1 dateFromString:result.createdDate];

4) Set Target time zone 
[timeFormatter1 setTimeZone:[NSTimeZone systemTimeZone]];
5) Set target date format 
[timeFormatter1 setDateFormat:@"dd-MM-yyyy hh:mm a"];
6) Get string from date
NSString *strTime = [timeFormatter1 stringFromDate:aDate];

试试这个。

NSString *strIncomingDate = @"29-Mar-2018 05:58:33";

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
[dateFormat setDateFormat:@"dd-MMM-yyyy hh:mm:ss"];
NSDate *date = [dateFormat dateFromString:strIncomingDate];

NSDateFormatter *dateFormat1 = [[NSDateFormatter alloc] init];
[dateFormat1 setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
[dateFormat1 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSString *strDesire = [dateFormat1 stringFromDate:date];