iMacHumphries
iMacHumphries

Reputation: 108

Formating NSDate to YYYYMMDDHHMMSS.XXX [gmt offset[:tz name]]

I am trying to create a date looks like this:

19961005132200.124[-5:EST]

Here is what I am trying:

+ (NSString *)getDate {
    NSDateFormatter* df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"YYYYMMDDHHMMSS.000[ZZ:zzz]"];

    NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    [df setTimeZone:gmt];
    return [df stringFromDate:[NSDate date]];
}

This is returning:

201604103050483.000[+0000:GMT]

Thanks in advance for the help!

Upvotes: 1

Views: 1229

Answers (2)

Tim007
Tim007

Reputation: 2557

The format string uses the format patterns Unicode Technical Standard #35

So

- (NSString *)getDate {
    NSDateFormatter* df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyyMMddHHmmss.SSS[Z:z]"];

    NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"EST"];
    [df setTimeZone:gmt];
    return [df stringFromDate:[NSDate date]];
}

Output

20160412021134.302[-0500:EST]

Option 2:

- (NSString *)getDate {
    NSDateFormatter* df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyyMMddHHmmss.SSS[Z:z]"];

    NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"EST"];
    [df setTimeZone:gmt];

    NSString *date = [df stringFromDate:[NSDate date]];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\d+\\.\\d+\\[[+-]?)(0?)(\\d)(\\d{2})(.*)" options:NSRegularExpressionCaseInsensitive error:nil];
    return [regex stringByReplacingMatchesInString:date options:0 range:NSMakeRange(0, date.length) withTemplate:@"$1$3$5"];
}

Output:

20160412021134.302[-5:EST]

Upvotes: 0

rmaddy
rmaddy

Reputation: 318884

Start by bookmarking the Unicode specification for date format specifiers.

Then look at each of the parts you need:

  • 4-digit year: yyyy
  • 2-digit month: MM
  • 2-digit day: dd
  • 24-hour 2-digit hour: HH
  • 2-digit minute: mm
  • 2-digit second: ss
  • 3-digit fractional second: SSS

There is a problem with the timezone since there is no specifier that will give you the part before the colon except with a leading zero. The closest you will get is: x:z.

Put all together you want: yyyyMMddHHmmss.SSS[x:z]

+ (NSString *)getDate {
    NSDateFormatter* df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyyMMddHHmmss.SSS[x:z]"];

    return [df stringFromDate:[NSDate date]];
}

Do not set the formatter's timezone if you want the output to be in the user's local timezone.

Upvotes: 2

Related Questions