Home > Mobile >  How to get Date with timezone as int?
How to get Date with timezone as int?

Time:01-09

how can I get date in this format in JS? I tried using .toISOString() but I don't quite get the result that I need.

2022-12-22 11:35:23 -0400

Thanks

CodePudding user response:

I don't know any fast way, but you can use something like this: To get a date in the format "YYYY-MM-DD HH:mm:ss ZZ" in JavaScript, you can use the following code:

const date = new Date();
const year = date.getFullYear();
const month = date.getMonth()   1; // months are zero-indexed, so we need to add 1
const day = date.getDate();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
const timeZoneOffset = date.getTimezoneOffset();
const timeZoneOffsetHours = Math.floor(Math.abs(timeZoneOffset) / 60);
const timeZoneOffsetMinutes = Math.abs(timeZoneOffset) % 60;
const timeZoneOffsetString = (timeZoneOffset < 0 ? ' ' : '-')  
    (timeZoneOffsetHours < 10 ? '0' : '')   timeZoneOffsetHours  
    ':'   (timeZoneOffsetMinutes < 10 ? '0' : '')   timeZoneOffsetMinutes;

const formattedDate = `${year}-${month < 10 ? '0' : ''}${month}-${day < 10 ? '0' : ''}${day} ${hours}:${minutes}:${seconds} ${timeZoneOffsetString}`;

This will give you a string like "2022-12-22 11:35:23 -0400".

CodePudding user response:

What format do you want? Did you use Date? Here is very useful library I use a lot. Date FNS there is format function and you can set format you want. Function returns string

  • Related