Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To be honest I thought this was a poor question until I read the last line. "I want the locale to only affect the order of the month, day and year. Can this be done?"</p> <p>A fixed date format such as <code>[formatter setDateFormat:@"HH:mm"]</code> will not be affected by locale changes. The best thing to do is to use a '<code>NSDateFormatterStyle</code>' to do the heavy lifting for you.</p> <p>Part of your problem was that you did not set the correct date formatter style. <code>NSDateFormatterShortStyle</code> already outputs the date format you want.</p> <p>As far as the time format goes, if the user has their system set to 24hour clock then <code>NSTimeZoneNameStyleShortGeneric</code> should work right out of the box. But if not that can be fixed. The beauty of it is you don't have to check.</p> <pre><code>// Example Date Now NSDate *now = [NSDate date]; // Formatter set to proper locale by default NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; // Set formatter to short styles [formatter setDateStyle:NSDateFormatterShortStyle]; [formatter setTimeStyle:NSTimeZoneNameStyleShortGeneric]; </code></pre> <p>At this point your formatter will have already setup it's own format string "<code>M/d/yy h:mm:ss a</code>", this would be for the US. So at this point all we have to do is change the format slightly.</p> <pre><code>// Remove the AM/PM from the format string formatter.dateFormat = [formatter.dateFormat stringByReplacingOccurrencesOfString:@"a" withString:@""]; // Change 12h clock to 24h clock formatter.dateFormat = [formatter.dateFormat stringByReplacingOccurrencesOfString:@"h" withString:@"H"]; </code></pre> <p>Now your date format should be "<code>M/d/yy H:mm:ss</code>". Which is the version you would want for the US. You can confirm with a log statement.</p> <pre><code>NSLog(@"%@",[formatter stringFromDate:now]); </code></pre> <p>Note that when you change the '<code>h</code>' in the format to '<code>H</code>' you don't care where it is. So if in some locale they were to have a reversed time format it would be changed, but left in it's original position.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload