Search code examples
javascriptdatedatetimeluxon

How to convert short dates to this format: DDD MMM DD YYYY GMT+0800 (X country standard time)?


When I do new Date() I get:

Thu Dec 28 2017 10:17:58 GMT+0800 (台北標準時間)

If I apply .valueOf() to that date I get:

1514427724039

Which is what I want.

Now, I need to apply .valueOf() to a date like this: 2017/12/28. I tried using Luxon to convert the date (since applying .valueOf() to YYYY/MM/DD doesn't produce a number):

DateTime.fromISO(startDate.replace(/\//g, '-')).toRFC2822()
// => Thu, 28 Dec 2017 00:00:00 +0800

However, applying valueOf() that results returns the same string. Not a number like in the first example.

What should I do so I can produce a numeric value from YYYY/MM/DD? Just I did with DDD MMM DD YYYY GMT+0800 (X country standard time)?


Solution

  • I think you're losing track of the types.

    fromISO() returns Luxon DateTime object, but toRFC2822 returns an RFC 2822 string representation of the date.

    So your valueOf() was being called on the string, not the DateTime.

    As others have pointed out, you need only call valueOf() on the result of fromISO().

    To illustrate:

    var dt = luxon.DateTime.fromISO('2017-12-05'); // returns a Luxon DateTime object
    console.log('fromISO returns an', typeof dt);
    
    var rfc = dt.toRFC2822(); // returns a string
    console.log('toRFC2822 returns a', typeof rfc);
    
    var valueOfRFC = rfc.valueOf(); // string.valueOf() is just that string
    console.log('strings are their own values?', rfc === valueOfRFC);
    
    var valueOfDT = dt.valueOf(); // this is what you want
    console.log('value of datetime', valueOfDT);
    <script src="https://moment.github.io/luxon/global/luxon.min.js"></script>