R0b0t0
R0b0t0

Reputation: 390

Javascript UTC Date different values

I have a date in the format dd.mm.yyyy

I use a function to convert this date to MM-DD-YYYY

stringToStringDateFormat(objectData: any): string {
    return moment(objectData, 'DD.MM.YYYY').format('MM-DD-YYYY');
}

I want to set hours minutes and seconds to 0 ad send the date in ISO format so i used the following code :

new Date(new Date(this.stringToStringDateFormat("19.07.2021")).setUTCHours(0,0,0,0)).toISOString();

yet the issue I have is I get a different day for example in this case I get 2021-07-18T00:00:00.000Z while in reality, it should be 2021-07-19T00:00:00.000Z

how can I get my code to get me the same date I provided and not the date -1 ?

Upvotes: 0

Views: 110

Answers (3)

RobG
RobG

Reputation: 147403

Parsing with a library to create an interim unsupported format then parsing with the built–in parser is not a good idea.

If you just want to reformat dd.mm.yyyy as yyyy-mm-ddT00:00:00Z then just reformat the string, there is no need to convert to Date object or use a library:

function reformatTimestamp(s) {
  return `${s.split(/\D/).reverse().join('-')}T00:00:00Z`;
}

console.log(reformatTimestamp('19.07.2021'));

Upvotes: 0

pilchard
pilchard

Reputation: 12919

Here using Date.UTC() and adjusting the month to account for zero index.

const [d, m, y] = `19.07.2021`.split('.').map(Number);

console.log(new Date(Date.UTC(y, (m - 1), d)).toISOString()); // months are 0 indexed

Upvotes: 2

Ameer
Ameer

Reputation: 2000

Created a new function that sets the hours, minutes, seconds and milliseconds to 0 and returns the date string in the correct format. See this answer for a more detailed look on the methods I used.

function stringToStringDateFormatStartDay(objectData) {
  const newD = moment(objectData, "DD.MM.YYYY").utcOffset(0).set({
    hour: 0,
    minute: 0,
    second: 0,
    millisecond: 0
  });
  newD.toISOString();
  newD.format("MM-DD-YYYY");
  return newD;
}

const d = stringToStringDateFormatStartDay("19.07.2021");
console.log(d)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Upvotes: 0

Related Questions