11

I did read different StackOverflow posts and they suggested to use .utc from moment but it doesn't work

Note: I am on PST zone

const start = '2018-06-10T21:00:00-04:00';
const end = '2018-06-10T23:00:00-04:00';
const noconversion = moment.utc(start).format('MM/DD/YYYY');
const converted = moment(end).format('MM/DD/YYYY');

Current output:

noconversion - 2018-06-11

converted - 2018-06-11

Output expected: 06/10/2018 just fetch date from date provided

CODEPEN Link

const date = '2018-06-16T00:00:00-04:00';
const oldConversion = moment(date).format('MM/DD/YYYY');
const newConversion = moment.parseZone(date).format('MM/DD/YYYY');
 
alert('********oldConversion**********'+ oldConversion);
alert('********newConversion**********'+ newConversion);
Nimantha
  • 6,405
  • 6
  • 28
  • 69
user2936008
  • 1,317
  • 5
  • 19
  • 42

3 Answers3

13

Have you tried parseZone?

moment.parseZone(end).format('MM/DD/YYYY');

That should keep your UTC offset applied. You can then also calculate the UTC offset, if you wanted to save that:

moment.parseZone(end).format('MM/DD/YYYY').utcOffset();
Phil Golding
  • 433
  • 3
  • 10
0

The solution I'm suggesting will ignore the timezone itself. It always take only the date. It might be a complex way to do it, but it always works for you.

const start = '2018-06-10T21:00:00-04:00'.split('-').slice(0, -1).join('-');
const end = '2018-06-10T23:00:00-04:00'.split('-').slice(0, -1).join('-');
const noconversion = moment(start).format('MM/DD/YYYY');
const converted = moment(end).format('MM/DD/YYYY');
Kamalakannan J
  • 2,818
  • 3
  • 23
  • 51
  • 1
    What if the timezone is not provided? This will fail in that case. I wouldn't take that risk. I would never muck with the string provided. – user2936008 Jul 25 '18 at 21:32
0

If you want to ignore timezone then why not from the string itself? This is just an out of the box thinking.

function convertToDate(date_string) {
    var date = date_string.indexOf('T') > -1 ? new Date(date_string.split('T')[0]) : date_string.indexOf(' ') > -1 ? new Date(date_string.split(' ')[0]) : new Date(date_string.substring(0,10));
    return (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear();
}

OR

function convertToDate(date_string) {
    var date = date_string.indexOf('T') > -1 ? date_string.split('T')[0].split('-') : date_string.indexOf(' ') > -1 ? date_string.split(' ')[0].split('-') : date_string.substring(0,10).split('-');
    return date[1] + "/" + date[2] + "/" + date[0];
}

const start = '2018-06-10T21:00:00-04:00';
const converted = convertToDate(start);
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Sookie Singh
  • 1,543
  • 11
  • 17