How to change format of date/time?

夙愿已清 提交于 2020-01-11 11:37:38

问题


I have this date and time format:

2010-05-19 07:53:30

and would like to change it to:

Wednesday @ 7:53PM 5/19/2010

I'm doing this, which gets the current format:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";

but when I change the format, I end up with a null. For example:

formatter.dateFormat = @"hh:mm tt MM-dd-yyyy";
date = [formatter stringFromDate:formattedDate];

date will be null. I want to put the end result into an NSString. It would be nice if time and date could come out as separate properties so I can arrange them however I like. Any ideas on how I can change the formatting?


回答1:


I think your formatting string is the problem. You should only use the characters you find in the table in UTS#35 Date Format Patterns. I tried your code and while the time hh:mm displays correctly, formatting stops at tt - not in the table!

If you really want characters in the format string that are not in the table you can escape them, like hh 'o''clock' a, zzzz - produces format like "12 o'clock PM, Pacific Daylight Time".




回答2:


It would be nice if time and date could come out as separate properties so I can arrange them however I like. Any ideas on how I can change the formatting?

You have things backwards. If this is a date/time to be displayed to the user, you need to present it how the user wants it, not how you want it. For instance, most people outside the USA will be confused by MM-dd-yyyy particularly if the day is less than 13. Consider using -setDateStyle: and -setTimeStyle:. That way, the display string will come out as the user expects.



来源:https://stackoverflow.com/questions/2871182/how-to-change-format-of-date-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!