Wayne Gilliver
Wayne Gilliver

Reputation: 135

Convert inputted time (which is PDT/PST) to local Time

So far I have created a timezone list for PST, CST, EST, GMT, CEST, IST, AST which works perfectly. But I also want to add an input box that will always be PST and output a local time from it..

i.e. if a user puts in 09:00 then if they live in the UK it will output 17:00 So it basically registers where you are in relation to timezone and adds (or subtracts) from the inputted time. (UK is +8 so input + 8 gives output)

This is my FIDDLE of where I am at right now

https://jsfiddle.net/wayneker/unc7e64f/16/

Although I know this demo is ideal, I know I cannot currently make this (with my current knowledge).

https://greenwichmeantime.com/time/to/pst-local/

I have researched various pages and cannot understand a lot of them. But what I have seen is normally local to PST

window.setInterval(function(){

// function to calculate local time
// in a different city
// given the city's UTC offset
function calcTime(offset) {
//function calcTime(city, offset) {

// create Date object for current location
d = new Date();

//set options
var options = { weekday: "short", year: "numeric", month: "short",
               day: "numeric", hour: "numeric", minute: "numeric", second: "numeric"  };

// convert to msec
// add local time zone offset 
// get UTC time in msec
utc = d.getTime() + (d.getTimezoneOffset() * 60000);

// create new Date object for different city
// using supplied offset
nd = new Date(utc + (3600000*offset));

// return time as a string
//return "The local time in " + city + " is " + nd.toLocaleString();
//return nd.toLocaleString();
return nd.toLocaleString("en-US", options);

}

Date.prototype.stdTimezoneOffset = function() {
var jan = new Date(this.getFullYear(), 0, 1);
var jul = new Date(this.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
Date.prototype.dst = function() {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
}
var today = new Date();
if (today.dst()) document.getElementById('dst').innerHTML = '';

Upvotes: 0

Views: 200

Answers (1)

user2818985
user2818985

Reputation: 390

Here is one way is to convert the PST time back to UTC and then apply the local offset.

function submitfunction() {

var value = document.getElementById("PSTPDT").value;

var parts = value.split(':');
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var date = now.getDate();
var offset = now.getTimezoneOffset()

var local = new Date(year, month, date, parts[0], parts[1], parts[2]);
local.setMinutes(local.getMinutes() + 420 - offset);

var result = document.getElementById("result");
result.innerHTML = local
}

See example: https://jsfiddle.net/p9u5j8dm/

Upvotes: 1

Related Questions