Frage

I have epoch times stored in my database like so: 1392821307. These were picked up on a separate web service using the php time() function. I need to convert this to a date/month/year format in Titanium.

So far I have used the following code based off an answer here in stack overflow

var utcSeconds = Jobs_data.Jobs[i].DatePosted;
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(utcSeconds);

This returns a string like so:

Wed Feb 19 14:48:27 GMT 2014

I only need the Feb 19 2014. So I'm wondering how to parse this string. I was going to use substring but then for example, Mon will have 3 letters and thurs will have 4, so the starting index of where to parse is changing. Not sure if the month will be of varying length also

War es hilfreich?

Lösung

d is actually a date object. If you pass that to Ti.API.info, or console.log, it'll be coerced in to the string that you see above. You should use its getDate, getMonth, and getFullYear methods to get the string that you want.

var formattedString = (d.getMonth()+1) + '/' + d.getDate() + '/' + d.getFullYear();

Alternatively, use moment.js, which is included in Alloy apps, and can be easily downloaded in to vanilla Titanium apps too:

var moment = require('alloy/moment'),
    dm = moment(d),
    formattedString = dm().format('L');

This is answered quite simply by a SO answer already:

Where can I find documentation on formatting a date in JavaScript?

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top