NSDateFormatter doesn't allow 24-hour format - iphone

I have to display the date in my app, where i need to display that only in the format of 12 - hour format, i have used this code to display the date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:kDateDisplayFormat];
NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
[dateFormatter setTimeZone:timeZone];
NSString *todaysDate = [NSString stringWithFormat:#"%#",[dateFormatter stringFromDate:[NSDate date]]];
[[self lblPointsDate] setText:todaysDate];
here when i change my iPhone date format to 24-hour it display's in 24-hour format. I need to convert 24-hour to 12-hour format or make it display only in 12-hour format. How can i do this?

Just switch
kDateDisplayFormat.dateFormat = #"HH:mm a";
to
kDateDisplayFormat.dateFormat = #"hh:mm a";

Although a solution is to use the 12-hour time format hh and not te 24-hour HH format why not let the user systems preference select the correct format:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateStyle = NSDateFormatterMediumStyle;
dateFormatter.timeStyle = NSDateFormatterShortStyle;
self.lblPointsDate.text = [dateFormatter stringFromDate:[NSDate date]]
Also there is no need to set the dateFormatter.timeZone to the system timezone, this is set by default.

Try the following:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:[NSDateFormatter dateFormatFromTemplate:#"hh:mm a" options:0 locale:[NSLocale currentLocale]]];
NSString *theTime = [dateFormatter stringFromDate:[NSDate date]];

Related

Identifying date format

"2014-02-03T23:10:00Z"
I'm aware of what each of the numbers represents, but the T and Z throw me off. Does anyone know what type of date format this is? I'd rather use a native parser if I could find one.
Thanks
It is an ISO 8601 format (http://en.wikipedia.org/wiki/ISO_8601).
T is Time delimeter while Z is used if time zone is UTC.
It appears to be ISO 8601 format. RestKit has a parser for it. You should also be able to get NSDateFormatter to parse it.
"2014-02-03T23:10:00Z" is the ISO 8601 format (http://www.w3.org/TR/NOTE-datetime)
the T represents the beginning of the time and the Z represents that the date is expressed in UTC (Coordinated Universal Time)
if you want to get the date with a specific format you could use NSDateFormatter
NSDate *now = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy/MM/dd"];
NSString *stringDate = [dateFormatter stringFromDate:date];
NSLog(#"%#", stringDate); // 2014/03/03
If you need just a certain part of the date (e.g just the current month):
NSDate *now = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM"];
NSInteger *monthNumber = [[dateFormatter stringFromDate:date] integerValue];
NSLog(#"%i", monthNumber); // 03
If you need the date in a specific language:
NSDate *now = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd' de 'MMMM' del 'yyyy"]; // You can add your own text between single quotes
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"es_ES"]];
NSString *stringDate = [dateFormatter stringFromDate:date];
NSLog(#"%#", stringDate); // 03 de febrero del 2014

How do I convert a string that contains "am/pm" to an NSDate when the user's device is set to 24-Hour Time in iOS?

I need to convert an NSString to an NSDate, but the following code only works as long as the user's device isn't set to 24-Hour time.
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"MM/dd/yyyy hh:mm:ss a"];
NSString *aTime = #"2/11/2013 12:00:00 AM";
NSDate *aDate = [formatter dateFromString:aTime];
However, aDate returns null when the device is in 24-Hour time. Any help?
I think you're probably seeing a side effect of the behaviour described by QA1480. Apple has resolved what it presumably thought was developers not obeying locales properly by modifying your prescribed date format unless you explicitly say not to.
You can achieve that by adding:
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
/* and autorelease if not using ARC */
Which basically says 'the date format I just set is explicitly what I want, please don't modify it in any way'.
I think the following snippet might helps you out.
NSString *dateString = #"09:34 AM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"dd-MM-yyyy";
NSString *stringFromDate = [dateFormatter stringFromDate:[NSDate date]];
dateFormatter.dateFormat = #"dd-MM-yyyy hh:mm a";
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
NSDate *returnDate = [dateFormatter dateFromString:[NSString stringWithFormat:#"%# %#", stringFromDate, dateString]];
try this code
NSString *string = #"2015-11-30 15:00:00";
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"yyyy-MM-dd HH:mm:ss";
[formatter setTimeZone:[NSTimeZone localTimeZone]];
NSDate *date = [formatter dateFromString:string];
date: 2015-11-29 21:30:00 +0000
its in UTC format you can modify this as you need!

How to get my time in UTC for iPhone project?

How to get my country time in UTC for iPhone development?
Here is the Code, Just Call below method when you want to set TimeZone and Date Format.
-(void)setDateFormat
{
NsDate myDate = [NSDate date];//here it returns current date of device.
//now set the timeZone and set the Date format to this date as you want.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
[dateFormatter setTimeZone:timeZone];
NSString *newDate = [dateFormatter stringFromDate:myDate];
// here you have new Date with desired format and TimeZone.
}
-(NSString *)UTCFormDate:(NSDate *)myDate
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
[dateFormatter setTimeZone:timeZone];
NSString *dateString = [dateFormatter stringFromDate:myDate];
return dateString;
}
Source:
https://stackoverflow.com/a/2615847/857865
[NSDate date] gives you the current point in time, which may be printed in UTC, GMT, EST or any other timezone. (Representation-wise, the current point in time is the number of seconds since a reference date in UTC.)
To get the current point in time in UTC as a string, get an NSDateFormatter and configure it to output a timestamp using the UTC timezone.

NSDateFormatter - does not respect 12/24 hour (am/pm) system setting in some circumstances

I want to output a date (that has relative dates, e.g. Today, Yesterday etc.) and time (respecting the 12/24 hours setting on the iOS device) E.g.
Today 5:48 PM (when in 12 hour mode); and
Today 17:48 (when in 24 hour mode)
Configuring an NSFormatter like this (and using stringFromDate:) does not work:
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale: [NSLocale autoupdatingCurrentLocale]];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle]; // doesn't respect am/pm setting on iOS device (grrr!)
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setDoesRelativeDateFormatting:YES]; // but does get relative dates
This gives you relative dates, but defaults to the 12/24 setting for the locale, e.g. 12 hours for US and 24 hours for UK. (Why Apple think UK people like 24 hours clocks, I don't know...)
A work around that I've adopted uses two NSDateFormatters, one for the date and one for the time. It appears that when you configure an NSDateFormatter with a dateStyle of NSDateFormatterNoStyle and a timeStyle of NSDateFormatterShortStyle, then it does respects the 12/24 hour setting. (So it's just when you have BOTH date and time styles set that there is trouble.)
I've included my work around below in case anyone else has a similar issue. Is there an easier way to do this? The work around seems somewhat awkward and it is not clear how confident I should be it will continue working in future revisions of iOS.
Work around
- (NSString*) humanRelativeDateAndTimeAlt: (NSDate*) date;
{
NSDateFormatter* relativeDateFormatter = [[NSDateFormatter alloc] init];
[relativeDateFormatter setLocale: [NSLocale autoupdatingCurrentLocale]];
[relativeDateFormatter setTimeStyle:NSDateFormatterNoStyle]; // no time for this formatter
[relativeDateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setDoesRelativeDateFormatting:YES]; // relative dates
NSString* datePart = [[self relativeDateFormatter] stringFromDate:date];
NSDateFormatter* timeDateFormatter = [[NSDateFormatter alloc] init];
[timeDateFormatter setLocale:[NSLocale autoupdatingCurrentLocale]];
[timeDateFormatter setDateStyle: NSDateFormatterNoStyle]; // no date for this formatter
[timeDateFormatter setTimeStyle: NSDateFormatterShortStyle]; // does respect 12/24 hour setting
NSString* timePart = [timeDateFormatter stringFromDate:date];
int skipZero = 0; // extra code to remove leading zero if present
if ([[timePart substringToIndex:1] isEqualToString:#"0"]) skipZero = 1;
[relativeDateFormater release];
[timeDateFormatter release];
return [NSString stringWithFormat:#"%# %#", datePart, [timePart substringFromIndex:skipZero]];
}
The reason for this behaviour is Locale, set the correct Locale, Set the local of your NSDateFormatter to en_US_POSIX will fix this.
It works for both 24-hour and 12 hour format.
From Apple doc:
On iPhone OS, the user can override the default AM/PM versus 24-hour time setting (via Settings > General > Date & Time > 24-Hour Time), which causes NSDateFormatter to rewrite the format string you set.
Reference: What is the best way to deal with the NSDateFormatter locale “feature”?
I have run into the same issue. I've raised it as a bug with Apple, and posted it on Open Radar:
http://openradar.appspot.com/9774877
I found this solution :
NSDate *now = [[NSDate alloc] init];
NSTimeZone *localTimeZone = [NSTimeZone systemTimeZone];
NSDateFormatter *rfc3339DateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[rfc3339DateFormatter setLocale:enUSPOSIXLocale];
[rfc3339DateFormatter setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'ssZ"];
[rfc3339DateFormatter setTimeZone:localTimeZone];
NSString *dateString = [rfc3339DateFormatter stringFromDate:now];
NSLog(#"RFC 3339 datetime: %#", dateString);
// 2013-06-27T10:27:08-0600
// 2013-07-22T15:09:30+0100
That fixed 2 of my problems :
When user is setted to 12h display mode, output with this formatter is display as 24h
When you manually set to Dublin timezone, output does not display dateTime with Z but +0000
I had a similar issue, what I ended up doing was to ammend the dateFormat, rather than specifying the timeStyle.
NSDateFormatter *formatter = [[ NSDateFormatter alloc ] init];
if (self.datePickerMode == UIDatePickerModeDateAndTime){
[formatter setDateFormat:[NSString stringWithFormat:#"%# %#", f.dateFormat, #"HH:mm:ss"]];
}
Worked well for me, hope it helps.
Use this format
NSDateFormatter* relativeDateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd hh:mm a";
NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];
Instad of HH (Hour in day (0-23)) use hh (Hour in am/pm (1-12))
Add a (Am/pm marker) in the end of the format.
For example: [NSDate date] is 2017-05-14 12:40:00
In 24-Hour time you will get 2017-05-14 12:40
In 12-Hour time you will get 2017-05-14 12:40 PM
For Today | Yesterday I use NSDateComponents for calculate and return right date.
NSCalendarUnit units = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute;
NSDateComponents *components = [[NSCalendar currentCalendar] components:units fromDate:yourDate toDate:[NSDate date] options:0];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
if (components.year > 0) {
dateFormatter.dateFormat = [NSString stringWithFormat:#"'%#' '%#' MMM d, YYYY", [#"last seen" localized], [#"at" localized]];
}
else if (components.day > 7) {
dateFormatter.dateFormat = [NSString stringWithFormat:#"'%#' MMM d '%#' hh:mm a", [#"last seen" localized], [#"at" localized]];
}
NSString *relativeDateString = [dateFormatter stringFromDate: yourDate];

iphone sdk:how to convert arabic date format to english?

I am working on an application in which I save the current Date in the database but when my app runs in Arabic language the current date format is changed into Arabic. I mean the date format should be like this 09/02/2010 but the digits are converted to Arabic digits. So how do I convert them back to English digits even if my app running in the Arabic Language?
In general it's best to keep dates in an agnostic type and only format them when they must be displayed. A common format is storing the number of seconds since 1970, or another date you choose.
E.g. the following code will display the current time correctly formatted for the users local.
NSDate* now = [NSDate dateWithTimeIntervalSinceNow:0];
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[NSLocale currentLocale]];
NSString* localDateString = [formatter stringFromDate];
[formatter release];
However when you do have a date in a locale-specific format, you can again use the formatter class to convert it. E.g.
NSString* localDate = #"09/02/2010"; // assume this is your string
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[NSLocale currentLocale]];
NSDate* date = [formatter dateFromString: localDate];
[formatter release];
For working with any type of locale-specific data (dates, currency, measurements) then the formatter classes are your friend.
i found it here i did it like this
NSDate *CurrentDate = [NSDate date];
NSDateFormatter *Formatter=[[NSDateFormatter alloc] init];
NSLocale *indianLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[Formatter setLocale:indianLocale];
[Formatter setDateFormat:#"dd/MM/yyyy"];
NSString *FormattedDate=[Formatter stringFromDate:CurrentDate];
[indianLocale release];
[Formatter release];
Try this
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:#"EST"];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:#"YYYY-MM-dd HH:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate:localDate];
Swift
dateFormatter.locale = NSLocale(localeIdentifier: "en_US") as Locale!
dateFormatter.dateFormat = "dd/MM/yyyy"
let resultsDate = dateFormatter.string(from: date)