• Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Post job
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

128
Views
How to get current date for timezone in javascripts

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.

about 1 year ago · Juan Pablo Isaza
2 answers
Answer question

0

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/

about 1 year ago · Juan Pablo Isaza Report

0

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

Or you can use 3rd party library like MomentJS.

about 1 year ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.