I used this snippet to convert a given date to a string. But if the date happens to have a time of less than 5:00 then the result is a prior date. For example, this date: "07-01-15 05:00:00 +0000" will work correctly. But a "07-01-15 04:49:00 +0000" will have a prior date as the result.
Any suggestions?
+(NSString *)stringFromGivenDate:(NSDate *)date
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"MM-dd-yy";
NSString *dateString = [dateFormatter stringFromDate:date];
NSLog(#"date: %#", dateString);
return dateString;
}
NSDateFormatter by default sets the time zone to your locale time zone.
But while converting date to string changes the time to GMT time.
So you have to set the time zone using
dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"]
or whatever timezone you want(like #"GMT+5:30").
So your code will be like:
+(NSString *)stringFromGivenDate:(NSDate *)date
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"MM-dd-yy";
dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"]
NSString *dateString = [dateFormatter stringFromDate:date];
NSLog(#"date: %#", dateString);
return dateString;
}
Related
I have Issue in dateformatter. I add my code as below:
NSDate *currentDate = [NSDate date];
NSLog(#"Current Date: %#",currentDate); //Current Date: 2016-10-14 08:07:15 +0000
NSTimeZone *timeZone = [NSTimeZone localTimeZone];
NSString *tzName = [timeZone name];
NSLog(#"Current TimeZone: %#",tzName); //Current TimeZone: Asia/Kolkata
NSTimeZone *systemTimeZone = [NSTimeZone systemTimeZone];
NSString *SyTZName = [systemTimeZone name];
NSLog(#"System TimeZone: %#",SyTZName); //System TimeZone: Asia/Kolkata
NSString *strCurrentDate = [NSString stringWithFormat:#"%#",[NSDate date]];
NSLog(#"Current Date: %#",strCurrentDate);//Current Date: 2016-10-14 08:07:47 +0000
NSDateFormatter* localDateFrm = [[NSDateFormatter alloc] init] ;
[localDateFrm setTimeZone:[NSTimeZone timeZoneWithName:#"IST"]];
[localDateFrm setDateFormat:#"dd-MM-yyyy hh:mm a"];
NSString* local_string = [localDateFrm stringFromDate:currentDate];
NSLog(#"local_string: %#",local_string);//local_string: 14-10-2016 01:37 PM
NSDateFormatter* local_dateFormatter = [[NSDateFormatter alloc] init] ;
[local_dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"IST"]];
[local_dateFormatter setDateFormat:#"dd-MM-yyyy hh:mm a"];
NSDate *date = [local_dateFormatter dateFromString:local_string];
NSLog(#"date : %#",date);//date : 2016-10-14 08:07:00 +0000
at last I need 01:37 PM but I get 08:07:00 +0000.when I convert string into NSDate its not give me expected reply(01:37 PM). so the time is different.
so please help me for this.
Thanks.
NSDate will always return utc or gmt date, if you want it to in your local timezone then you need to convert it to string with stringFromDate method of NSDateFormatter.
So, when you want to display your date with your local timezone just convert it to string and then show. And when you want it to as NSDate you can easily convert string to date with dateFromString method and it will return date in utc or gmt again.
And usually you need to display your date in label or any UI so you must need string, you can't show nsdate on label. So, this is standard approach to deal with NSDate
Update :
You can use this date as localnotification's firedate also. execute below demo,
NSString *str = #"2016-10-14 08:07:00";
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"yyyy-MM-dd hh:mm:ss"];
NSDate *date = [df dateFromString:str];
NSLog(#"date : %#",[df dateFromString:str]);
UILocalNotification *notification = [[UILocalNotification alloc]init];
notification.fireDate = date;
notification.alertTitle = #"title";
NSLog(#"notification : %#",notification);
and check log for notification, it will show firetime as per your local timezone!!
Second thing you can set timezone also for notification like notification.timeZone = ...;
I am getting a date time from web service which is in UTC format. Now i want to assign it to NSDate. Following is the code i have done
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss"];
NSDate *utcDate = [dateFormatter dateFromString:#"2015-08-18T23:00:00"];
but it is calculating its timezone calculations by default the result is 2015-08-19 03:00:00 +0000. How can i initialize NSDate with same date and Time. I want to perform timezone calculations later on
edit/update:
Xcode 11 • Swift 5.1:
let dateString = "2015-08-18T23:00:00"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
if let dateFromString = formatter.date(from: dateString) {
print(dateFromString) // "2015-08-18 23:00:00 +0000"
}
A default-allocated NSDateFormatter will use the current locale (the one that the user set up in Settings.app).
You have to explicitly set a suitable locale on the formatter:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
This locale uses the gregorian calendar on UTC without any DST adjustments.
Edit: LeoDabus points out that setting the locale does not change the timezone of the date formatter. This has to be done explicitly:
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
NSString *dateStr =[NSString stringWithFormat:#"%#",[dict valueForKey:#"utc_datetime"]];
NSString* input = dateStr;
NSString* format = #"dd MMM yyyy - HH:mm:ss'";
// Set up an NSDateFormatter for UTC time zone
NSDateFormatter* formatterUtc = [[NSDateFormatter alloc] init];
[formatterUtc setDateFormat:format];
[formatterUtc setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
// Cast the input string to NSDate
NSDate* utcDate = [formatterUtc dateFromString:input];
// Set up an NSDateFormatter for the device's local time zone
NSDateFormatter* formatterLocal = [[NSDateFormatter alloc] init];
[formatterLocal setDateFormat:format];
[formatterLocal setTimeZone:[NSTimeZone localTimeZone]];
// Create local NSDate with time zone difference
NSDate* localDate = [formatterUtc dateFromString:[formatterLocal stringFromDate:utcDate]];
NSLog(#"utc: %#", utcDate);
NSLog(#"local: %#", localDate);
NSDateFormatter *format1q = [[NSDateFormatter alloc] init];
format1q.dateFormat = #"HH:mm";
NSString *StrDAte=[NSString stringWithFormat:#"%#",[format1q stringFromDate:utcDate]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"HH:mm";
NSDate *date = [dateFormatter dateFromString:StrDAte];
date = [date dateByAddingTimeInterval:-60];
dateFormatter.dateFormat = #"hh:mm a";
NSString *pmamDateString = [dateFormatter stringFromDate:date];
Actually, I would like to change below string to date, When I'm trying to do this, I'm getting nil date.
Example 1:
Input:
Tue 20 May 2014 09:30:00 PM IST
Looking for/Output : 09 PM (Only Time and AM/PM)
Example 2:
"Tue 20 May 2014 10:00:00 AM CDT"
Output : 10 AM
NSString *dateString=#"20 May 2014 09:30:00 PM IST";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"EEE dd MMM yyyy HH:mm:ss a zzzz";
NSDate *time= [formatter dateFromString:dateString];
//above time object is getting nil
Anybody can you please help me how to change above string to date/time format. I tried many ways But I'm getting nil date object when i'm trying to convert string to date.
Here is how you are going to want to handle this:
NSString * dateString = #"Tue 20 May 2014 10:00:00 AM IST";
NSString *threeLetterZone = [[dateString componentsSeparatedByString:#" "] lastObject];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithAbbreviation:threeLetterZone];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"EEE dd MMM yyyy hh:mm:ss a z";
NSDate *date;
if (timeZone)
{
NSString *gmtTime = [dateString stringByReplacingOccurrencesOfString:threeLetterZone withString:timeZone.abbreviation];
date = [formatter dateFromString:gmtTime];
}
NSLog(#"%#", date);
I know its a lot longer but this will return the GMT time of the string.
EDIT:
Cocoa is weird. You won't be able to preserve the timezone. Everything revolves around the GMT/UTC
If you want the local time:
NSString * dateString = #"Tue 20 May 2014 10:00:00 AM IST";
NSString *threeLetterZone = [[dateString componentsSeparatedByString:#" "] lastObject];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithAbbreviation:threeLetterZone];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"EEE dd MMM yyyy hh:mm:ss a";
NSDate *date;
if (timeZone)
{
NSString *gmtTime = [dateString stringByReplacingOccurrencesOfString:threeLetterZone withString:#""];
date = [formatter dateFromString:gmtTime];
}
NSLog(#"%#", date);
It looks like there is a subset of time zone abbreviations that work, mainly abbreviations that are tied to a country, not a region. Even timezone abbreviations such as CET (Central European Time) do not work but CST (Cuban Standard Time) does. This makes some sense since 12 vs 24 hour time is usually tied to a country, not a timezone.
There is another problem here, that is the use of English abbreviations: "Tue" and "May".
Here is a version based on the answer by #Chase Walden that does not use GMT. The key element is the same, getting the `NSTimeZone from the string. It is a bit longer.
NSString * dateString = #"Tue 20 May 2014 10:00:00 AM IST";
NSMutableArray *components = [NSMutableArray arrayWithArray:[dateString componentsSeparatedByString:#" "]];
NSString *threeLetterZone = [components lastObject];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithAbbreviation:threeLetterZone];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"EEE dd MMM yyyy hh:mm:ss a"];
if (timeZone) {
[components removeLastObject];
dateString = [components componentsJoinedByString:#" "];
[formatter setTimeZone:timeZone];
}
NSDate *date = [formatter dateFromString:dateString];
NSLog(#"%#", date);
2014-05-20 04:30:00 +0000
Here how you should do this in Objective C.
Igone the setTimeZone by the date formatter if you don't want any time zone changes.
NSString *inputDate = #"WhateverTheTime";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"CurrentDateTimeFormat"];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"IST"]]; //Only if you want to change the timeZone
NSDate *date = [formatter dateFromString:inputDate];
[formatter setDateFormat:#"RequiredDateTimeFormat"];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]]; //Only if you want to change the timeZone
NSString *requiredOutput = [formatter stringFromDate:date];
Cheers!!
I have string #"2/10/2014 10:12:12 AM" (month/day/year hour:minute:second am/pm) in this format. How to convert it into NSDate format.
I feel it easy but not getting in same format.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"MM/dd/yyyy hh:mm:ss a";
NSString *dateString = #"12/24/2014 10:32:42 PM";
NSDate *date = [formatter dateFromString:dateString];
NSLog(#"date: %#", [formatter stringFromDate:date]);
Next thing you'll need to figure out is the time zones.
I have weird result trying to output NSDate object from NSString.
My NSString is: 1976-06-11
My method to convert is:
-(NSDate*)dateFromString:(NSString *)dateString{
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormat dateFromString:dateString];
return date;
}
But it output 1976-06-10 21:00:00 +0000
How could that happen? Difference in 1 day.
You have date in UTC format. Use this code to converting your date to local time:
NSTimeInterval seconds; // assume this exists
NSDate *ts_utc = [NSDate dateWithTimeIntervalSince1970:seconds];
NSDateFormatter *utcFormatter = [[NSDateFormatter alloc] init];
utcFormatter.timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
utcFormatter.dateFormat = #"yyyy.MM.dd G 'at' HH:mm:ss zzz";
NSDateFormatter *localFormatter = [[NSDateFormatter alloc] init];
localFormatter.timeZone = [NSTimeZone timeZoneWithName:#"EST"];
localFormatter.dateFormat = #"yyyy.MM.dd G 'at' HH:mm:ss zzz";
NSString *utcDateString = [utcFormatter stringFromDate:ts_utc];
NSString *LocalDateString = [localFormatter stringFromDate:ts_utc];
Or you can use [NSTimeZone defaultTimeZone] to prevent hardcoded strings for timezone names. This method returns the system time zone, If no default time zone has been set.
You can use following methods to convert an UTC date string into UTC date and local date
- (NSDate *)convertIntoGMTZoneDate:(NSString *)dateString
{
NSDateFormatter *gmtFormatter = [[NSDateFormatter alloc]init];
[gmtFormatter setDateStyle:NSDateFormatterFullStyle];
[gmtFormatter setTimeStyle:NSDateFormatterFullStyle];
[gmtFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
return [gmtFormatter dateFromString:dateString];
}
- (NSDate *)convertIntoSystemZoneDate:(NSString *)dateString
{
NSDateFormatter *systemZoneFormatter = [[NSDateFormatter alloc]init];
[systemZoneFormatter setDateStyle:NSDateFormatterFullStyle];
[systemZoneFormatter setTimeStyle:NSDateFormatterFullStyle];
[systemZoneFormatter setTimeZone:[NSTimeZone systemTimeZone]];
return [systemZoneFormatter dateFromString:dateString];
}
func dateFromString(dateString: String) -> NSDate {
// Convert string to date object
var dateFormat = NSDateFormatter()
dateFormat.dateFormat = "yyyy-MM-dd"
dateFormat.timeZone = NSTimeZone(name: "UTC")
var date = dateFormat.dateFromString(dateString)!
print(date)
return date
}
output :
1976-06-11 00:00:00 +0000
If you debug code, it shows 1 day difference but after run you will find the actual date which is you enter.
It works for me.I think it will helps you.
Thank you