i have api returns data including timestamp record. in swift have timestamp element loaded , converted double , can convert time. want able return time if date of record today , return date if record not today. see below:
let unixtimestring:double = double(rowdata["timestamp"] as! string)! let date = nsdate(timeintervalsince1970: unixtimestring) // on est time , has not yet been localised. var dateformatter = nsdateformatter() dateformatter.timestyle = .shortstyle dateformatter.doesrelativedateformatting = true // if date today display time, if date not today display date , change text color grey. var stringtimestampresponse = dateformatter.stringfromdate(date) cell.timestamplabel.text = string(stringtimestampresponse)
do use nscalendar see if 'date' today , something? how localise time correct user rather server time?
there handy function on nscalendar tells whether nsdate in today or not (requires @ least ios 8) isdateintoday()
to see working, put playground:
// create couple of unix dates. let timeintervaltoday: nstimeinterval = nsdate().timeintervalsince1970 let timeintervallastyear: nstimeinterval = 1438435830 // show dates are. let = nsdate(timeintervalsince1970: timeintervaltoday) let = nsdate(timeintervalsince1970: timeintervallastyear) // function show formatted date timestamp func displaytimestamp(ts: double) -> string { let date = nsdate(timeintervalsince1970: ts) let formatter = nsdateformatter() formatter.timezone = nstimezone.systemtimezone() if nscalendar.currentcalendar().isdateintoday(date) { formatter.datestyle = .nostyle formatter.timestyle = .shortstyle } else { formatter.datestyle = .shortstyle formatter.timestyle = .nostyle } return formatter.stringfromdate(date) } // should show time. displaytimestamp(timeintervaltoday) // should show date. displaytimestamp(timeintervallastyear)
or, if want see looks without running yourself:
Comments
Post a Comment