Weird converting output from NSString to NSDate - ios

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

Related

dateFromString returns nil. Unable to convert the date to the desired format

This is my input nsstring 30/01/18 3:25 PM
I want the date in this format : 30/Jan/18 3:25 PM.
This is what i tried :
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter setDateFormat:#"dd/MM/yy HH:mm "];
NSDate *date = [[NSDate alloc] init];
date = [dateFormatter dateFromString:releaseDate];
[dateFormatter setDateFormat:#"dd/MMM/yy HH:mm "];
NSString *finalDate = [dateFormatter stringFromDate:date];
Also i tried this :
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yy HH:mm z"];
NSDate *date = [[NSDate alloc] init];
date = [dateFormatter dateFromString:releaseDate];
[dateFormatter setDateFormat:#"dd/MMM/yy HH:mm z"];
NSString *finalDate = [dateFormatter stringFromDate:date];
I am always getting date as nil !! What am i doing wrong?
Also : Time comes in both 12 hour format and 24 hour format. How do i handle both at the same time?
You check it below function, its working fine: -
-(void)DateChange
{
NSString *Input_Date =#"31/01/18 04:25 AM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/mm/yy hh:mm a"];
NSDate * Format_date = [dateFormatter dateFromString:Input_Date];
[dateFormatter setDateFormat:#"dd/MMM/yy hh:mm a"];
NSString *Change_date = [dateFormatter stringFromDate:Format_date];
NSLog(#"Final Change Date :- %#",Change_date);
}
My Output is :-
Final Change Date :- 31/Jan/18 04:25 AM
Use this function written in Swift to change the date format. Its working not
func dateFormatterfromString(_ date: String!) -> String{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MMM-yyyy"
let date = dateFormatter.date(from:date)!
dateFormatter.dateFormat = "yyyy-MM-dd"
let dateString = dateFormatter.string(from:date)
return dateString
}

coversion of date and time from 31 May 2016 04:30 PM(current format) to 2016-05-31T16:30:00.000+05:30(Required format)

hi can any on help me in achiving this is the string which i have 31 May 2016 04:30 PM(NSSTring) 2016-05-31T16:30:00.000+05:30(Required Format)
NSString *dateString = dateandtime;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
used the following code but returns nil
The current format string does not contain any time zone information, so you have to set the time zone in the date formatter as well as the locale to be able to parse the string independently from the current locale.
The input format is dd MMM yyyy hh:mm a
NSString *dateString = #"31 May 2016 04:30 PM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:#"en_US_POSIX"];
dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:19800];
dateFormatter.dateFormat = #"dd MMM yyyy hh:mm a";
NSDate *dateFromString = [dateFormatter dateFromString:dateString];
dateFormatter.dateFormat = #"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
NSString *stringFromDate = [dateFormatter stringFromDate:dateFromString];
Some how I tried and worked
NSString *myString = dateandtime;
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"dd MMM yyyy hh:mm a";
NSDate *yourDate = [dateFormatter dateFromString:myString];
dateFormatter.dateFormat = #"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ";
NSLog(#"%#",[dateFormatter stringFromDate:yourDate]);
Whatever you do, test that your code works if the user doesn't use an Indian timezone, and if the user uses 24 hour time instead of AM/PM on their phone. I assume your "dateandtime" was created by converting an NSDate to an NSString; it would be much better to not do that but start with the original NSDate.
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
NSString *currentDateString = #"2016-05-31T16:30:00.000+05:30";
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ"];
NSDate *currentDate = [dateFormatter dateFromString:currentDateString];
NSLog(#"CurrentDate:%#", currentDate);
you can use this code.

iOS - Init NSDate with a stringDate without timezone calculations

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];

Convert NSDate to NSString with a small bug

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;
}

NSDate time converting from 12hr to 24 hr format

hi i have problem while converting Date Formats...
the date time is in the Format 12 hour Format like 12/9/2010 4:00:00 PM
(Month/date/year Hour:Min:sec Pm)
i need to Convert it into 24 hour format like 12/9/2010 16:00:00
Can any one Help me please....
Thx in advance
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateformatter.dateFormat = #"hh:mm a";
NSDate *date = [dateformatter dateFromString:departTime];
dateformatter.dateFormat = #"HH:mm";
NSString *time24 = [dateformatter stringFromDate:date];
departTimelbl.text=time24;
Simply do This to get 24 hour time format (In Swift 2)
let formatter = NSDateFormatter()
formatter.dateFormat = "HH:mm a" //(hh:mm a----> for 12 hour format)
let timeString = formatter.stringFromDate(NSDate())
print(timeString)
UPDATE: Swift 3 version
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm a" //(hh:mm a----> for 12 hour format)
let timeString = formatter.string(from: Date())
print(timeString)
You need to use a NSDateFormatter. I encourage you to read the class reference as linked by Kay.
Here's how you'd do it. I'm assuming the date is originating as a NSString.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM-dd-yyyy HH:mm:ss"];
NSDate *myDate = [df dateFromString:yourNSString];
NSString *myNewDate = [formatter stringFromDate:myDate];
[formatter release];
[myDate release];
Use these functions,this will change the date string from 12 to 24 hr formate and 24 to 12hr formate.
-(NSString *)changeformate_string24hr:(NSString *)date
{
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setTimeZone:[NSTimeZone systemTimeZone]];
[df setDateFormat:#"MM/dd/yyyy hh:mm:ss a"];
NSDate* wakeTime = [df dateFromString:date];
[df setDateFormat:#"MM/dd/yyyy HH:mm:ss"];
return [df stringFromDate:wakeTime];
}
-(NSString *)changeformate_string12hr:(NSString *)date
{
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setTimeZone:[NSTimeZone systemTimeZone]];
[df setDateFormat:#"MM/dd/yyyy HH:mm:ss"];
NSDate* wakeTime = [df dateFromString:date];
[df setDateFormat:#"MM/dd/yyyy hh:mm:ss a"];
return [df stringFromDate:wakeTime];
}
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"HH:mm";
NSDate *date = [dateFormatter dateFromString:#"15:15"];
dateFormatter.dateFormat = #"hh:mm a";
NSString *pmamDateString = [dateFormatter stringFromDate:date];
Take a look at NSDateFormatter class reference and the data formatting guide. There you will find more especially the method dateFromString and stringFromDate are interesting for you. There is another question dealing with similar problem From string with locale to date on iphone sdk where you can find some sample code when you want to set a special formatting template string.
In Swift
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy hh:mm:ss a"
var date: Date? = dateFormatter.date(from: "12/9/2010 4:00:00 PM")
dateFormatter.dateFormat = "MM/dd/yyyy HH:mm:ss"
var convertedString: String? = nil
if let aDate = date {
convertedString = dateFormatter.string(from: aDate)
}
In Objective C
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"MM/dd/yyyy hh:mm:ss a";
NSDate *date = [dateFormatter dateFromString:#"12/9/2010 4:00:00 PM"];
dateFormatter.dateFormat = #"MM/dd/yyyy HH:mm:ss";
NSString *convertedString = [dateFormatter stringFromDate:date];

Resources