0

how to change the server date time to local date time using javascript.

I am using following function for getting the server time.Now i want to change this time to local time zone.

function getTimeZoneAndServerDateTime() {

    var context = SP.ClientContext.get_current();
    var web = context.get_web();
    var timeZone = web.get_regionalSettings().get_timeZone();
    context.load(timeZone);
    context.executeQueryAsync(
    function onSucceeded() {
        var info = timeZone.get_information();
        var offset = (info.get_bias() + info.get_daylightBias()) / 60.0;
        var serverDateTimeNow = new Date(new Date().getTime() - offset * 3600 * 1000).toISOString();
        console.log("serverDateTimeNow: " + serverDateTimeNow);
    },
     Failure
    );

}
2

javascripts Date will give you the local time on the client.

var now = new Date();
0
var serverOffsetTime = "";

function serverDefaultDateTime()
{
    var clientContext = new SP.ClientContext.get_current();
    this.timeZone = clientContext.get_web().get_regionalSettings().get_timeZone();
    clientContext.load(timeZone);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onGetServerOffsetTimeSuccess), Function.createDelegate(this, this.onQueryFailed));
}

function onGetServerOffsetTimeSuccess(){
    var info = timeZone.get_information();  
    serverOffsetTime=(info.get_bias());
    var clientDate=new Date();
    var clientOffsetTime=(clientDate.getTimezoneOffset());
    var timedifference=(serverOffsetTime-clientOffsetTime)/60;
    var serverDateTimeNow = new Date(new Date().getTime() - (timedifference * 3600 *1000));
    return  serverDateTimeNow;
}

function removeServerOffsetTime(userDate) /* userDaTe -- is server date and time*/
{
    var clinetLocalDate=new Date();
    var clientOffsetTime=(clinetLocalDate.getTimezoneOffset());
    var timedifference=(serverOffsetTime-clientOffsetTime)/60;
    var localDateTimeNow = new Date(userDate.getTime() + (timedifference * 3600 *1000));
return localDateTimeNow;
}
0

Once you have retrieved the value form the Date field using JS, use the method "localeFormat()" to convert it to the local time zone and format as desired. Below are a few examples.

console.log(targetListItem.get_item('Created').localeFormat());
console.log(targetListItem.get_item('Created').localeFormat("dd/MM/yyyy HH:mm:ss"));

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.