Victor Molina
Victor Molina

Reputation: 2641

Moment.js moment().local() doesn't return my local time

Introduction

I am currently in Spain and my UTC offset is +1 hours. I have seen there is a method in moment.js that converts a given date to a local date... Click here to see this method in the documentation

CODE

I am doing this:

const relativeToUserDate = moment().local();

Problem

And when I console log this I am not getting my local time.

console.log(relativeToUserDate.locale()) // "en"
console.log(relativeToUserDate) // "2020-09-02T16:28:06.550Z" -- My real local time is: 2020-09-02T18:28:06.550Z

What am I doing wrong? I will really appreciate your help.

Thanks.

Upvotes: 0

Views: 1902

Answers (2)

trincot
trincot

Reputation: 350270

The final console.log outputs an object. You should convert to string with

relativeToUserDate.format()

If you get .toDate() you'll get the current date/time also. Note that internally JavaScript stores dates as UTC, and it uses your locale to determine how to display it with methods like toLocaleString. You should always use methods on these date objects to tell it what exactly you want. Don't output the objects as-is.

Upvotes: 1

Ryan Wolton
Ryan Wolton

Reputation: 71

It looks like the local method is used to convert a UTC date to a local date, what does moment().format() give you? pretty sure moment() should already use your local time.

Upvotes: 1

Related Questions