- (NSString*)formatDateTime
{
NSDate *now = [[NSDate alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd;MM;yyyy;HH;mm;SS"];
NSString *dateTime = [dateFormatter stringFromDate:now];
return dateTime;
}
There are some tricky details here, about the format string. A valid and desired output for me would be something like 20;12;2012;20;04;22. But this code can actually deliver something like 20;12;2012;21;49;78. We surely don't want to show anything like 49 minutes and 78 seconds.
Let's see this, piece by piece. If you write @"DD;MM;yyyy;HH;mm;SS" you will obtain an output as 355;12;2012;20;04;22, because the capital D specifies day of the year (In this example, December 20th is the 355th day of the year 2012). So you should specify lower case d to obtain the day of the month (20 in my example). Capital M or MM for months will deliver the numerical value of the month of the year (1 for M, or 01 for MM, to 12). MMM will output the abbreviated form for the name of the month (for instance, "Dec") and MMMM will output the complete name of the month ("December").
A capital H specifies that you want to show the hour of the day in the range from 0 to 23. A lower case h will produce the hour in the range from 1 to 12. Lower case m or mm will produce the value of the minutes part of the hour, respectively paddled or not. Finally, a capital S will produce the fractional value of the seconds part of the hour, which means a decimal value that will make no sense for your user in most cases. A lower case s will deliver the expected value from 1 to 59.
Doubling d, m (for months), h, m (for minutes) and s, as we have already mentioned, will paddle the zero (01 to 09 instead of 1 to 9), which is usually the desired aesthetics. So my final formatting string becomes @"dd;MM;yyyy;HH;mm;ss".
I haven't spoke about the year part, but you should use yyyy instead of YYYY, to show the year with four digits (or yy, to have it with two digits). There is a technicality here. The capital Y actually specifies that you are using ISO 8601 year-week calendar, which in general will deliver the Gregorian calendar expected value, but exceptions are allowed. This is something that most of the time will not deserve your concern, but is an usual advice adopting the lower case format as a default.
Finally, these rules are not iOS or Mac specific. Actually, they come from Unicode Technical Standard #35, which means that, as a Unicode standard, they are pretty much ubiquitous.
Um abraço!
No comments:
Post a Comment