0

I pull data from a database and output JSON. Once of the items pulls a date entered in this format 2018-06-25

I tried this:

var date = new Date(element.rundate).toString().substring(0,15);

However the output subtracts a day like this Sun Jun 24 2018

Anyone know how to correct?

1
  • 3
    welcome to the problem with timezones Commented Jun 27, 2018 at 20:08

2 Answers 2

1

you can use moment.js or

const date = new Date(element.rundate)
result = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
Sign up to request clarification or add additional context in comments.

Comments

0

The problem is that when the date format is yyyy-mm-dd, JavaScript will parse it as an ISO 8601 date, so it will assume it's UTC 00:00.

However, if the date format is yyyy/mm/dd or mm-dd-yyyy it will use local time, according to the RFC 2822:

The date and time-of-day SHOULD express local time.

Therefore, replacing dashes - with slashes / will do the trick. Alternatively, you can also split the different parts of the date and create a new date string representation with the format mm-dd-yyyy, but I think the previous approach is more concise and cleaner:

// Original date:
const dashes = '2018-06-25';

// With slashes instead of dashes:
const slashes = dashes.replace(/-/g, '\/');

// mm-dd-yyyyinstead of dd-mm-yyyy:
const [ year, month, day ] = dashes.split('-');
const monthDayYear = `${ month }-${ day }-${ year }`;

// Output:
console.log(`${ dashes } => ${ new Date(dashes) }`);
console.log(`${ dashes } => ${ slashes } => ${ new Date(slashes) }`);
console.log(`${ dashes } => ${ monthDayYear } => ${ new Date(monthDayYear) }`);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.