How to Convert a Timestamp String to Local Time Using Javascript?

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

2

3 Answers

I figured it out myself and I am able to accomplish what I needed. Passing the timestamp from database to var new Date(timestamp) get it converted to local time, it takes care of timezone and offsets as well. Thanks for your time experts! :)

0

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

If you are going to use AngularJS, it will be much more easier and straightforward to convert from 1408648665 to Thu, 21 Aug 2014 19:17:45 GMT

    //html
    <div ng-controller="TimeCtrl">
      Date: {{timeStamp + '000' | date: 'medium'}}
    </div>

    //js
    var app = angular.module('myApp', []);
    app.controller('TimeCtrl', function time($scope) {
      $scope.timeStamp = 1408648665;
      console.log("hello");
    });

Fiddle:

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.