Santosh
Santosh

Reputation: 3837

Understanding the conversion of date and time to specific timezone

I have a date and time in api response. Which I need to convert in user timezone.

start_date_time

datetime: function (datetime) {
    return moment(datetime, 'YYYY-MM-DD HH:mm:ss').tz(timeZone).format('MMM Do YYYY, h:mm a');
},

However, the start_date_time are the same as it is in the response. Just the format is changed. If I changed to another timezone it works fine. My timezone is "Asia/Kolkata"

How do I let moment know that this date and time doesn't belong to "Asia/Kolkata" and needs to convert it in same?

Upvotes: 1

Views: 49

Answers (1)

Fraction
Fraction

Reputation: 12993

If the start_date_time is UTC time then you must add a Z at the end of it:

const start_date_time = "2019-04-20 02:00:00";
const timeZone = "Asia/Kolkata";
console.log(moment(start_date_time+"Z"));
console.log("Asia/Kolkata date: ", moment(start_date_time+"Z").tz(timeZone).format('MMM Do YYYY, h:mm a'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>

Otherwise you must first specify the timeZone of the start_date_time then you can convert it to another timezone:

const start_date_time = moment.tz("2019-04-20 02:00:00", "America/New_York");
console.log(start_date_time.format());

const timeZone = "Asia/Kolkata";
console.log("Asia/Kolkata date: ", start_date_time.tz(timeZone).format('MMM Do YYYY, h:mm a'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>

Upvotes: 2

Related Questions