Assume that I have string like this from server #"2014-03-08T16:59+0000".
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *date = [self dateFromJSONString:#"2014-03-08T16:59+0000"];
NSDateComponents *dateComponents = [calendar components:(NSTimeZoneCalendarUnit) fromDate:date];
NSLog(#"TimeZone is %#", [[dateComponents timeZone] abbreviation]);
But the TimeZone is not base on the string, it based on the currentTimeZone of the device.
Is it possible to extract timeZone from string ?
You have to parse the offset from GMT from your string yourself.
Something like this, but you'll have to tweak for your slightly different format:
/**
This is assuming format yyyy-MM-dd'T'HH:mm:ssZZZZZ . ie the last 5 chars are timezone offset from gtm in the form (+|-)##:##
*/
-(NSTimeZone*)timezoneFromDateString:(NSString*)dateString {
NSTimeZone *timezone = nil;
NSString *timezoneComponent = [dateString substringFromIndex:19];
if(timezoneComponent.length == 6) {
NSArray *components = [[timezoneComponent substringFromIndex:1] componentsSeparatedByString:#":"];
NSInteger offset = [[timezoneComponent substringToIndex:1] isEqualToString:#"-"] ? -1 : 1;
if(components.count == 2) {
offset *= [components[0] integerValue] * 60*60 + [components[1] integerValue] *60;
timezone = [NSTimeZone timeZoneForSecondsFromGMT:offset];
}
}
return timezone;
}
-(NSArray*)convertToLocalDate:(NSString*)dateStr{
NSArray *convert;
NSString *time=#"";
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:#"MM/dd/yyyy hh:mm:ss a"];
NSDate *date = [dateFormatter1 dateFromString:dateStr];
//NSLog(#"date : %#",date);
NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"UTC"];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:date];
NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:date];
NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset;
NSDate *destinationDate = [[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:date] ;
NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
[dateFormatters setDateFormat:#"dd.MM.yyyy"];
[dateFormatters setTimeZone:[NSTimeZone systemTimeZone]];
dateStr = [dateFormatters stringFromDate: destinationDate];
NSDateFormatter *dateFormatters1 = [[NSDateFormatter alloc] init];
[dateFormatters1 setDateFormat:#"hh:mm a"];
[dateFormatters1 setTimeZone:[NSTimeZone systemTimeZone]];
time = [dateFormatters1 stringFromDate: destinationDate];
convert = [[NSArray alloc ]initWithObjects:dateStr,time,nil];
return convert;
}
If you are sure that the string you need to parse is always formatted in that way, then regexes provide a simple way to do it:
NSString *str = #"2014-03-08T16:59+0000";
NSString *pattern = #"^.*T\\d{2}:\\d{2}";
NSString *timezone = [str stringByReplacingOccurrencesOfString: pattern
withString: #""
options: NSRegularExpressionSearch
range: NSMakeRange(0, str.length)];
Related
I have string 2015-08-10T12:00 how can I convert it to Date?
My code did not works
[self.dataFormatter setDateFormat:#"yyyy-MM-ddTHH:mm"];
NSDate *date = [self.dataFormatter dateFromString:dateStg];
Use this date format:
yyyy-MM-dd'T'HH:mm
converted current Date into String
//Get Current Date
NSLocale *en_US_POSIX = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
assert(en_US_POSIX != nil);
NSDate *currentTime = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:en_US_POSIX];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSString *resultString = [dateFormatter stringFromDate: currentTime];
Converted Current Time inTo NSString
//Get Current Date
NSDate* now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *dateComponents = [gregorian components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:now];
NSInteger hour = [dateComponents hour];
NSString *am_OR_pm=#"AM";
if (hour>12){
hour=hour%12;
am_OR_pm = #"PM";
}
NSInteger minute = [dateComponents minute];
NSString *strTime=[NSString stringWithFormat:#"%02d:%02d %#", hour, minute ,am_OR_pm];
Converted NSString to NSDate
NSString *dateString = #"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:dateString];
I have a webservice that returns the date in this format:
2013-04-14
How do i figure out what day this corresponds to?
This code will take your string, convert it to an NSDate object and extract both the number of the day (14) and the name of the day (Sunday)
NSString *myDateString = #"2013-04-14";
// Convert the string to NSDate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd";
NSDate *date = [dateFormatter dateFromString:myDateString];
// Extract the day number (14)
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:date];
NSInteger day = [components day];
// Extract the day name (Sunday)
dateFormatter.dateFormat = #"EEEE";
NSString *dayName = [dateFormatter stringFromDate:date];
// Print
NSLog(#"Day: %d: Name: %#", day, dayName);
Note: This code is for ARC. If MRC, add [dateFormatter release] at the end.
An alternate method for getting the weekday can be:
NSString *myDateString = #"2013-04-14";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:myDateString];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:date];
NSInteger weekday = [components weekday];
NSString *weekdayName = [dateFormatter weekdaySymbols][weekday - 1];
NSLog(#"%# is a %#", myDateString, weekdayName);
You can use this code it working for me.
NSString *dateString = #"2013-04-14";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter setDateFormat:#"EEEE"];
NSLog(#"%#", [dateFormatter stringFromDate:dateFromString]);
If you have 2013-04-14 stored in a NSString called date, then you can do this...
NSArray *dateComponents = [date componentsSeperatedByString:#"-"];
NSString *day = [dateComponents lastObject];
Swift 3:
let datFromat = DateFormatter()
datFormat.dateFormat = "EEEE"
let name = datFormat.string(from: Date())
Bonus: If you want to set your own date template instead of using Date() above:
let datFormat = DateFormatter()
datFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let thisDate = datFormat.date(from: "2016-10-13T18:00:00-0400")
Then call the 1st code after this.
I have an app where i want to provide a list of UTC timezone so that the user could select destination time. I have all the country abbreviations in picker view. But i want UTC abbreviations.
Can anyone please suggest me how could i achieve this.
Thanks
You can use the knownTimeZoneNames property of NSTimeZone for all timezones.
[NSTimeZone knownTimeZoneNames]
Or you can use abbreviationDictionary for getting all abbreviations
[[NSTimeZone abbreviationDictionary] allKeys]
If you want time of these timezones, the use the below code
NSArray *abbs = [[NSTimeZone abbreviationDictionary] allKeys];
for (id eachObj in abbs) {
NSString *dateStr = [self dateFromTimeZoneAbbreviation:eachObj];
NSLog(#"%#",dateStr);
}
define the method as
-(NSString *)dateFromTimeZoneAbbreviation:(NSString *)abb {
NSString *dateStr;
NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
NSTimeZone* timeZoneFromAbbreviation = [NSTimeZone timeZoneWithAbbreviation:abb];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:[NSDate date]];
NSInteger gmtOffset = [timeZoneFromAbbreviation secondsFromGMTForDate:[NSDate date]];
NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset;
NSDate *destinationDate = [[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:[NSDate date]] ;
NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
[dateFormatters setDateFormat:#"dd-MMM-yyyy hh:mm"];
/*[dateFormatters setDateStyle:NSDateFormatterShortStyle];
[dateFormatters setTimeStyle:NSDateFormatterShortStyle];
[dateFormatters setDoesRelativeDateFormatting:YES];*/
[dateFormatters setTimeZone:[NSTimeZone systemTimeZone]];
dateStr = [dateFormatters stringFromDate: destinationDate];
NSLog(#"DateString : %#, TimeZone : %#", dateStr , timeZoneFromAbbreviation.abbreviation);
return dateStr;
}
NSLog(#"%#", [NSTimeZone knownTimeZoneNames]);//viewDidLoad
for(id timezone in [NSTimeZone knownTimeZoneNames]){
NSLog(#"%#",[self getTimeZoneStringForAbbriviation:timezone]);
NSLog(#"%#", timezone);
}
-(NSString*)getTimeZoneStringForAbbriviation:(NSString*)abbr{
NSTimeZone *atimezone=[NSTimeZone timeZoneWithName:abbr];
int minutes = (atimezone.secondsFromGMT / 60) % 60;
int hours = atimezone.secondsFromGMT / 3600;
NSString *aStrOffset=[NSString stringWithFormat:#"%02d:%02d",hours, minutes];
return [NSString stringWithFormat:#"GMT%#",aStrOffset];
}
I have a webservice that returns the date in this format:
2013-04-14
How do i figure out what day this corresponds to?
This code will take your string, convert it to an NSDate object and extract both the number of the day (14) and the name of the day (Sunday)
NSString *myDateString = #"2013-04-14";
// Convert the string to NSDate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd";
NSDate *date = [dateFormatter dateFromString:myDateString];
// Extract the day number (14)
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:date];
NSInteger day = [components day];
// Extract the day name (Sunday)
dateFormatter.dateFormat = #"EEEE";
NSString *dayName = [dateFormatter stringFromDate:date];
// Print
NSLog(#"Day: %d: Name: %#", day, dayName);
Note: This code is for ARC. If MRC, add [dateFormatter release] at the end.
An alternate method for getting the weekday can be:
NSString *myDateString = #"2013-04-14";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:myDateString];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:date];
NSInteger weekday = [components weekday];
NSString *weekdayName = [dateFormatter weekdaySymbols][weekday - 1];
NSLog(#"%# is a %#", myDateString, weekdayName);
You can use this code it working for me.
NSString *dateString = #"2013-04-14";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter setDateFormat:#"EEEE"];
NSLog(#"%#", [dateFormatter stringFromDate:dateFromString]);
If you have 2013-04-14 stored in a NSString called date, then you can do this...
NSArray *dateComponents = [date componentsSeperatedByString:#"-"];
NSString *day = [dateComponents lastObject];
Swift 3:
let datFromat = DateFormatter()
datFormat.dateFormat = "EEEE"
let name = datFormat.string(from: Date())
Bonus: If you want to set your own date template instead of using Date() above:
let datFormat = DateFormatter()
datFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let thisDate = datFormat.date(from: "2016-10-13T18:00:00-0400")
Then call the 1st code after this.
i have a string like 2013-03-05T07:37:26.853 and i want to get the Output : 2013-03-05 07:37:26. I want the final output in NSDate object. i am using below function to convert desire output. and it returning wrong time.
- (NSDate *) getDateFromCustomString:(NSString *) dateStr
{ NSArray *dateStrParts = [dateStr componentsSeparatedByString:#"T"];
NSString *datePart = [dateStrParts objectAtIndex:0];
NSString *timePart = [dateStrParts objectAtIndex:1];
NSArray *dateParts = [datePart componentsSeparatedByString:#"-"];
NSArray *timeParts = [timePart componentsSeparatedByString:#":"];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setHour:[[timeParts objectAtIndex:0] intValue]];
[components setMinute:[[timeParts objectAtIndex:1] intValue]];
[components setSecond:[[timeParts objectAtIndex:2] intValue]];
[components setYear:[[dateParts objectAtIndex:0] intValue]];
[components setMonth:[[dateParts objectAtIndex:1] intValue]];
[components setDay:[[dateParts objectAtIndex:2] intValue]];
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSDate *date = [currentCalendar dateFromComponents:components];
NSLog(#"Date 1:%#",date); // Returns wrong time (2013-03-05 02:07:26)
/* i had tried the below.
NSDateFormatter * format = [[NSDateFormatter alloc] init];
[format setTimeZone:NSTimeZoneNameStyleStandard];
[format setDateFormat:#"yyyy-MM-dd hh:mm:ss"];
NSLog(#"Date 2:%#",[format stringFromDate:date]); // Returns correct date (2013-03-05 07:37:26)
NSDate *fDate = [format dateFromString:[format stringFromDate:date]];
DLog(#"Date 3:%#",fDate); // Returns wrong time (2013-03-05 02:07:26)
*/
[components release];
return date;
}
Plz suggest me if any idea.
What you're seeing here is a time zone issue. If you want to NSLog a correct looking date, we'll need to give the input string a GMT time zone:
Add this in your code and see what happens:
[components setTimeZone: [NSTimeZone timeZoneForSecondsFromGMT: 0]];
Try this,
NSString *departTimeDate = #"2013-03-05T07:37:26.853";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS"];
NSDate *date = [dateFormatter dateFromString:departTimeDate];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSLog(#"Expected Result___ %#",[dateFormatter stringFromDate:date]); //2013-03-05 07:37:26
Try this : issue is Time zone.
+ (NSDate *) getDate:(NSString *) dateStr
{
NSArray *dateStrParts = [dateStr componentsSeparatedByString:#"T"];
NSString *datePart = [dateStrParts objectAtIndex:0];
NSString *timePart = [dateStrParts objectAtIndex:1];
NSString *t = [[timePart componentsSeparatedByString:#"."] objectAtIndex:0];
NSString *newDateStr = [NSString stringWithFormat:#"%# %#",datePart,t];
//2013-03-05 07:37:26
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [df dateFromString:newDateStr];
DLog(#"%#",date);
return date;
}