Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a timestamp string to local time using javascript?

I have a JSP page in which I am pulling timestamp stored in database as string which has the form Thu Aug 21 2014 22:09:23 GMT+0530 (India Standard Time).

Of Course, I am able to display it as it is in the page, however I was looking for a solution in javascript that would enable me convert this timestamp as per user's local timezone.

Is there a way to do this ? Or for such a timestamp it's not possible ? Any help is greatly appreciated, well my question may sound silly as I am still familiarizing myself with javascript.

Thanks

like image 625
Raghvendra Kumar Avatar asked Aug 21 '14 19:08

Raghvendra Kumar


People also ask

How do you convert timestamps to time?

Simply multiply Unix timestamp by 1000 to convert it to a JavaScript time, because Unix timestamp measures time as a number of seconds, whereas in JavaScript time is fundamentally specified as the number of milliseconds (elapsed since January 1, 1970 at 00:00:00 UTC).

How do you convert a string to a date in JavaScript?

You can Convert the date value from String to Date in JavaScript using the `Date()`` class. You can also use parse, which is a static method of the Date class. You can also split the given string date into three parts representing the date, month, and year and then convert it to Date format.

How do I convert a string to a date?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.


1 Answers

You may try this

var timezone = new Date().getTimezoneOffset();

From MDN

The time-zone offset is the difference, in minutes, between UTC and local time. Note that this means that the offset is positive if the local timezone is behind UTC and negative if it is ahead. For example, if your time zone is UTC+10 (Australian Eastern Standard Time), -600 will be returned. Daylight savings time prevents this value from being a constant even for a given locale

Also here is an interesting article which may help you:- Auto detect a time zone with JavaScript

EDIT:

var d = new Date(myYear, myMonth, myDate);
d.setTime( d.getTime() + d.getTimezoneOffset()*60*1000 );
like image 152
Rahul Tripathi Avatar answered Sep 20 '22 13:09

Rahul Tripathi