I need to convert a 12 Hour time format to 24 Hour format. Specifically the PM part of a date, as the API I communicate with only accepts 24-hour format.
Example:
02:00 PM needs to be converted to 14:00.
08:30 PM needs to be converted to 20:30.
I've tried several approaches and probably been close, but I can't seem to get it quite right.
For that you need to use NSDateFormatter and convert the time format to 24 Hours format.
NSString *time12Hours = #"02:00 PM";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"hh:mm a"];
NSDate *date = [formatter dateFromString:time12Hours];
[formatter setDateFormat:#"HH:mm"];
NSString *time24Hours = [formatter stringFromDate:date];
iPhone format strings are in Unicode format. Behind the link is a table explaining what all the letters above mean so you can build your own.
You can try this website for find your format string nsdateformatter.com whit NSDateFormatter
Related
I'm converting 12 hour date to 24 here, but it failed to get perfect time.
Here is code :
NSString *dateStr = #"2016-08-12T04:10:14.915Z";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd'T'hh:mm:ss.SSS'Z'"];
[dateFormat setTimeZone:[NSTimeZone localTimeZone]];
NSDate *date = [dateFormat dateFromString:dateStr];
and my final date is
2016-08-11 22:40:14 +0000
How ?
The NSDate object that you are getting is GMT. In France GMT -2, if I run your code I have a time of 02:10.
Am I correct assuming your GMT offset is -5:30 ?
NSDate objects don't have time zones; they represent an absolute
moment in time. However, when you ask one for its description (by
printing it in an NSLog, e.g.), it has to pick a time zone. The most
reasonable "default" choice is GMT. If you're not in GMT yourself, the
date will seem to be incorrect, by the amount of your own offset.
You should always use an NSDateFormatter, setting its timezone to
yours, before displaying a date.
Don't trust what NSLog or the debbuger are telling you about a NSDate.
use
NSString dateAsString = [dateFormat stringFromDate:date];
to check your date :)
trying to convert NSString to NSDate
NSString *startDateForCal='09-03-2016 08:00:00 AM'
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat: #"dd-MM-yyyy HH:mm:ss a"];
NSDate * EventStart = [dateFormatter dateFromString: startDateForCal];
But getting mixed result as "2016-03-09 18:30:00 +0000" returning date as correct but time didn't match with string It would be welcome any suggestions
Thank you
it should be
[dateFormatter setDateFormat: #"dd-MM-yyyy hh:mm:ss a"];
i.e. no capital HH for hour. HH return the Hour in 24 format
For more details Click now
and regarding the error in date,
since you have set the time format wrong( as HH instead of hh), it took the time as 12:00 AM and showed it in GMT timezone(IST - 5 and half hours, so in your case 12:00 AM - 5:30 = 18:30 of previous day), i guess you haven't set the locale properly.
setting the locale(in swift),
dateFormatter.locale = NSLocale(localeIdentifier:"en_IN")
Your question makes no sense. Your goal was to obtain an NSDate from an NSString. You did that, and you did it successfully.
How you discover what that NSDate is, is a completely different matter. It is represented to you by default (in the console) in a certain time zone and format. But that is irrelevant; it is still the same date, and it is the correct date.
I'm having a problem. I get incoming time strings in 12-hour format, and I'm turning them into NSDate objects. When the iPhone is in 12 hour format, no problem. But when it's in 24 Hour format, things go wrong. Here's some sample code to demonstrate:
NSString *theTime = #"3:19 PM";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"h:mm a"]; // "3:19 PM"
NSDate *date = [formatter dateFromString:theTime];
NSString *theString = [formatter stringFromDate:date];
In 24 hour mode, date is 1970-01-01 03:19:00, and theString is "3:19" - WRONG
In 12 hour mode, date is 1970-01-01 15:19:00, and theString is "3:19 PM" - RIGHT
So... question 1: why is the device's 24 hour setting overriding my date formatter setting?
and more importantly, question 2: How do I get a proper conversion from 12 hour time to 24 hour time?
I already have code to detect if the phone is in 24 hour mode, but other than digging around in the string and swapping the 3 with a 15, there doesn't seem to be a clean way to do this.
Not sure if you still need it, but I've had a similar problem which got solved by setting the locale for the date formatter. That is, if you want to force it to 12-hour mode, regardless of the user's 24/12 hour mode setting, you should set the locale to en_US_POSIX.
The reason for this behaviour is Locale, set the correct Locale
NSString *strAgendaDate = #"01/17/2012 12:00 AM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"] autorelease];
[dateFormatter setDateFormat:AgendaDateFormatForMeeting];
NSDate *meetingDate = [dateFormatter dateFromString:aStrDate];
[dateFormatter setDateFormat:AgendaDateRepresentation];
strAgendaDate = [dateFormatter stringFromDate:meetingDate];
It works for both 24-hour and 12 hour format
I believe the #"h:mm a" should be #"HH:mm a".
If you use the pre-build dateformatter in cocoa, everything will be taken care of for you.
NSDateFormatter *timeFormatter = [[[NSDateFormatter alloc] init] autorelease];
[timeFormatter setTimeStyle:NSDateFormatterShortStyle];
[timeFormatter setDateStyle:NSDateFormatterNoStyle];
NSDateFormatterShortStyle and NSDateFormatterNoStyle comes in different varieties.
Using those will make sure you respect the settings the user has selected for dates and times.
The 12-14 hour clock conversion is taken care of by the SDK, if you have a model or some value object for storing your dates try to keep them as NSDate. This way you can format them only when you need to display them. Saving dates as strings could open a world of trouble when you maybe parse them from xml where the GMT is specified separately or try to add and subtract NSTimeIntervals.
I changed from #"hh:mm:ss" to #"HH:mm:ss" and time style was changed from "1:03 PM" to "13:03".
Hope this will help you.
Okay, I left a comment, but it squished all the code together, so I'll have to "answer" my question with a comment:
Thanks. I gave it a whirl with this code:
NSString *theTime = #"3:19 PM";
NSDateFormatter *timeFormatter = [[[NSDateFormatter alloc] init] autorelease];
[timeFormatter setTimeStyle:NSDateFormatterShortStyle];
[timeFormatter setDateStyle:NSDateFormatterNoStyle];
NSDate *date = [timeFormatter dateFromString:theTime];
NSString *theString = [timeFormatter stringFromDate:date];
And date comes up nil. I ran into this earlier when I tried this route, and it's not working. Very frustrating.
I have an NSDate:
2015-07-13 16:04:01 +0000
and I want to convert it to an NSString to be able to store it on a server and then read it back from server and convert back to NSDate without losing any details.
I've been looking at other posts that have suggested doing it as follows:
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *dateString = [dateFormatter stringFromDate:date];
and vice-versa:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSDate *dateFromString = [dateFormatter dateFromString:message[#"date"]];
but this leads to the loss and compromise of the format:
Jul 13, 2015
How do I convert NSDate to NSString and back, eventually getting back the exact original NSDate?
You're only formatting the original NSDate with a date (not time) style that reflects the user's preferences and you're only formatting the retrieved NSDate with day, month, and year, i.e. "dd-MM-yyyy". You should be consistent your NSDateFormatters in order to maintain the original format.
Change both
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
and
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
to
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss Z"];
to get and keep the entire date and time format.
An NSDate stores the number of seconds since a reference date. If you are using only iOS applications. then you call a method returning that number of seconds as an NSTimeInterval which is a number, and then you store the number. This means there is absolutely no loss of information. Your data will come back with better than microsecond precision.
If the data has to be read by different devices not running iOS then there is another method returning the number of seconds since Jan 1st, 1970. This is a very standard format that any OS should be able to handle.
Storing a number instead of a string seems to be much better.
How can I output human readable dates like turn NSDATE to human readable form like Tomorrow, one week from now, 1 month from now , etc?
For example if the current time is January 19, 2012 7 am
and the input date is January 20, 2012 9am
then the function should out Tomorrow at 9am.
I found how to do this with past dates online but not with future dates.
Also the functions I found online were not specific. Any help would be appreciated! thanks
You need to use an NSDateFormatter. From the docs:
setDoesRelativeDateFormatting: Specifies whether the receiver uses
phrases such as “today” and “tomorrow” for the date component.
- (void)setDoesRelativeDateFormatting:(BOOL)b
Parameters b YES to specify that the receiver should use relative date
formatting, otherwise NO. Discussion If a date formatter uses relative
date formatting, where possible it replaces the date component of its
output with a phrase—such as “today” or “tomorrow”—that indicates a
relative date. The available phrases depend on the locale for the date
formatter; whereas, for dates in the future, English may only allow
“tomorrow,” French may allow “the day after the day after tomorrow,”
as illustrated in the following example.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSLocale *frLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"fr_FR"];
[dateFormatter setLocale:frLocale];
[dateFormatter setDoesRelativeDateFormatting:YES];
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:60*60*24*3];
NSString *dateString = [dateFormatter stringFromDate:date];
NSLog(#"dateString: %#", dateString);
// Output
// dateString: après-après-demain