dmaulikr
dmaulikr

Reputation: 468

How to Get Date, Hour, Minute and Second in Objective-c from Timestamp "2017-04-30T14:30+00:00(GMT)"?

I'm new in iOS(Objective-c) coding and I'm stuck at timestamp. I'm getting timestamp while JSON parsing ie.2017-04-30T14:30+00:00(GMT). How to get date, hour, minute and second from this timestamp?? I'm getting this format in GMT so, is it possible to convert it into "IST"? How?

Upvotes: 0

Views: 2346

Answers (1)

Suresh D
Suresh D

Reputation: 4295

Date Format Patterns
A date pattern is a string of characters, where specific strings of characters are replaced with date and time data from a calendar when formatting or used to generate data for a calendar when parsing. The following are the characters used in patterns to show the appropriate formats for a given locale. The following are examples:

enter image description here

- (NSString *)curentDateStringFromDate:(NSDate *)dateTimeInLine withFormat:(NSString *)dateFormat {
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];

    [formatter setDateFormat:dateFormat];

    NSString *convertedString = [formatter stringFromDate:dateTimeInLine];

    return convertedString;
}

Use it like below:

NSString *dateString = [self curentDateStringFromDate:[NSDate date] withFormat:@"dd-MM-yyyy"];
NSString *timeString = [self curentDateStringFromDate:[NSDate date] withFormat:@"hh:mm:ss"];
NSString *hoursString = [self curentDateStringFromDate:[NSDate date] withFormat:@"h"];

In the Foundation framework, the class to use for this task (in either direction) is NSDateFormatter Refer here

The code below convert GMT to IST.

NSString *inDateStr = @"2000/01/02 03:04:05";
NSString *s = @"yyyy/MM/dd HH:mm:ss";

// about input date(GMT)
NSDateFormatter *inDateFormatter = [[NSDateFormatter alloc] init];
inDateFormatter.dateFormat = s;
inDateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSDate *inDate = [inDateFormatter dateFromString:inDateStr];

// about output date(IST)
NSDateFormatter *outDateFormatter = [[NSDateFormatter alloc] init];
outDateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"IST"];
outDateFormatter.dateFormat = s;
NSString *outDateStr = [outDateFormatter stringFromDate:inDate];

// final output
NSLog(@"[in]%@ -> [out]%@", inDateStr, outDateStr);

Upvotes: 2

Related Questions