user2936008
user2936008

Reputation: 1347

Moment js - get date without considering time zone

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);

Upvotes: 11

Views: 18168

Answers (3)

Sookie Singh
Sookie Singh

Reputation: 1623

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);

Upvotes: 0

Kamalakannan J
Kamalakannan J

Reputation: 2998

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');

Upvotes: 0

Phil Golding
Phil Golding

Reputation: 471

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();

Upvotes: 13

Related Questions