ios - swift - Convert a String to a Date and then to a String in a different format -
suppose have simple string, extracted array of strings (representing dates) -
var mydatestring = "2015-11-25 04:31:32.0"
now, want convert string looks nov 25, 2015.
for that, assume need -
- get nsdate date object string using nsdateformatter
- get string nsdate object using functionality (which i've been unable find)
i've been trying in playground, have been unable solve such simple problem.
here have tried -
line 1| var dateformatter = nsdateformatter() line 2| dateformatter.locale = nslocale.currentlocale() line 3| dateformatter.dateformat = "yyyy-mm-dd hh:mm:ss.a" line 4| let somedate = dateformatter.datefromstring(str) line 5| let somedatestring = dateformatter.stringfromdate(somedate!)
in sidebar of xcode, line 4 prints "nov 25, 2015, 12:00 am"
, when try print string somedate
, "2015-11-25 00:00:00.0"
.
i haven't found single proper explanation of nsdates anywhere.
this easier in java parse()
, format()
functions dates.
updated swift 3.0
you need 2 date formatters - 1 make sense of input string , convert nsdate, , different formatter create output string
let mydatestring = "2016-01-01 04:31:32.0" let dateformatter = dateformatter() dateformatter.dateformat = "yyyy-mm-dd hh:mm:ss.a" let mydate = dateformatter.date(from: mydatestring)! dateformatter.dateformat = "mmm dd, yyyy" let somedatestring = dateformatter.string(from: mydate)
i have updated answer change date formatter yyyy yyyy. in cases, there no difference between two, yyyy may treat first few days of year being part of last complete week of previous year.
the apple developer guides explain this.
a common mistake use yyyy. yyyy specifies calendar year whereas yyyy specifies year (of “week of year”), used in iso year-week calendar. in cases, yyyy , yyyy yield same number, may different. typically should use calendar year.
Comments
Post a Comment