如何解析可能采用两种不同日期格式的日期字符串,并在iOS和Android中将其显示为本地时间?

时间:2023-01-22 08:37:21

I’m getting a date string in two different time formats as the following:

我正在以两种不同的时间格式获取日期字符串,如下所示:

yyyy-MM-dd’T'HH:mm:ss.SSS'Z’ like 2015-03-05T05:57:58.854Z and yyyy-MM-dd’T’HH:mm:ss.SSSZ like 2015-03-05T11:27:58 +0530.

yyyy-MM-dd'T'HH:mm:ss.SSS'Z'如2015-03-05T05:57:58.854Z和yyyy-MM-dd'T'HH:mm:ss.SSSZ如2015-03- 05T11:27:58 +0530。

I have to parse the string and display the time in the local timezone. How do I parse a date string which may be in two different date formats and display it to local time?

我必须解析字符串并在本地时区显示时间。如何解析可能采用两种不同日期格式的日期字符串并将其显示为当地时间?

1 个解决方案

#1


0  

You can try with parsing with a format first, if the it gives you a date object, use that, otherwise use the other format. A rough draft for iOS will be as follow:

您可以先尝试使用格式解析,如果它为您提供了日期对象,请使用该格式,否则使用其他格式。适用于iOS的草稿如下:

NSDate* dateFromString(NSString *string){
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    //try with first format
    [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
    //convert the date
    NSDate *date = [formatter dateFromString:string];

    //check if the first format worked or not
    if (!date) {
        //try with the other format.
        [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
        //return the converted date
        return [formatter dateFromString:string];
    }
    return date;
}

You'll be calling it like this:

你会这样称呼它:

NSDate *aDate = dateFromString( @"2015-03-05T05:57:58.854Z");
NSDate *anotherDate =dateFromString( @"2015-03-05T11:27:58 +0530");

Use the same technique for android.

对android使用相同的技术。

#1


0  

You can try with parsing with a format first, if the it gives you a date object, use that, otherwise use the other format. A rough draft for iOS will be as follow:

您可以先尝试使用格式解析,如果它为您提供了日期对象,请使用该格式,否则使用其他格式。适用于iOS的草稿如下:

NSDate* dateFromString(NSString *string){
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    //try with first format
    [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
    //convert the date
    NSDate *date = [formatter dateFromString:string];

    //check if the first format worked or not
    if (!date) {
        //try with the other format.
        [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
        //return the converted date
        return [formatter dateFromString:string];
    }
    return date;
}

You'll be calling it like this:

你会这样称呼它:

NSDate *aDate = dateFromString( @"2015-03-05T05:57:58.854Z");
NSDate *anotherDate =dateFromString( @"2015-03-05T11:27:58 +0530");

Use the same technique for android.

对android使用相同的技术。