I have a pattern format of timezone as below "2021-10-29T18:01:23 07:00", and so I want to get the current time with the same time zone as above, can someone help me with this problem,
I tried this code but it doesn't work
new Date().toGMTString()
Thank you so much.
CodePudding user response:
In generall I would recommend looking into MomentsJS. It is very helpfull when working with Date. It comes with Format Functions and also with features where you can safely add or deduct Date.
MomentJS Docs: https://momentjs.com/
CodePudding user response:
With native Date
methods, the closest you can get is with use of:
new Date().toISOString() // '2021-11-02T13:12:26.229Z'
But this returns GTM time, to obtain local time in your specified pattern, you have to format it yourself:
function formatDateString(date) {
//Function to format numbers (prepending leading zero and adding sign)
const f = (n, sign = false) => (sign ? (n < 0 ? "-" : " ") : "") n.toLocaleString('en-US', { minimumIntegerDigits: 2, useGrouping: false });
//Compute Date, Time and Zone
const d = `${date.getFullYear()}-${f(date.getMonth() 1)}-${f(date.getDate())}`;
const t = `${f(date.getHours())}:${f(date.getMinutes())}:${f(date.getSeconds())}`;
const z = `${f(-date.getTimezoneOffset() / 60, true)}:00`;
//Return it all together
return `${d}T${t}${z}`;
}
var mydate = new Date();
console.log(mydate.toISOString());
console.log(formatDateString(mydate));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Or you can use 3rd party library like MomentJS.