How to switch seconds to a specific time zone? - javascript

I receive the variable, which is seconds. The following code I could switch seconds to date and time. The time zone is Europe where I'm now, but I have to switch it to Asian time zone. I tried add toLocaleString() behind new Date(secOfCookie * 1000), it didn't work. Could anyone give me some help? Thanks!
.toLocaleString("en-US", {
timeZone: "Asia/Tokyo",
timeZoneName: "long",
});
function getTimeSwitchTokyoTime(secOfCookie) {
let date = new Date(secOfCookie * 1000)
let hours = date.getHours()
let minutes = "0" + date.getMinutes();
let seconds = "0" + date.getSeconds();
let formattedTime = date + hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
return formattedTime
}
getTimeSwitchTokyoTime(1665224574)
//'Sat Oct 08 2022 12:22:54 GMT+0200 (Central European Summer Time)12:22:54'

I found the way, actually I thought it too complicated..
It's actually easy.
Date(millisecond) could directly switch millisecond to date, and which base on the timezone where I am.
Then I use toLocaleString() to switch to the timezone I want.
new Date(secOfCookie * 1000).toLocaleString(
"en-US",
{
timeZone: "Asia/Tokyo",
timeZoneName: "long",
})
``

Related

javascript how to change date now format [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 2 years ago.
I am facing an issue with javascript dates. I want to change the format of date
this.setState({
current: Date(Date.now()),
}, 1000);
//convert minutes
//if minutes are 0 to 29 then show current hours reset the minutes again start with 0 like 18:00
//if minutes are 29 to 59 then show current hours reset the minutes again start with 30 like 18:30
var slotTime1 = currentdate.getHours() +':'+ (currentdate.getMinutes() <= 29 ? '00' : '30') ; //10:30
Output:
Thu May 14 2020 10:00:30 GMT+0500 (Pakistan Standard Time)
Expected
10:00:52 AM
10:30 AM
What should I change?
You can simply use Date toLocaleTimeString() method like:
const current = new Date()
const timestring = current.toLocaleTimeString()
console.log( timestring ) //=> 10:47:52 AM
The toLocaleTimeString() method returns a string with a language sensitive representation of the time portion of the date.
To only get hh:mm a format you can pass option object to the toLocaleTimeString() method like:
const current = new Date()
const timestring = current.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
console.log( timestring ) //=> 10:50 AM
With setState:
this.setState({
current: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
});
var date=new Date();
console.log(date.getHours() + ":" + date.getMinutes()+ ":" + date.getSeconds() + " " + date.getHours()<12 ? 'AM' : 'PM'}`);
OUTPUT : 11:9:37 AM
date.getHours()<12 results in AM between 12Am to 11:59 AM and after 11:59 it results in PM

how to get this specific datetime format in javascript

In javascript, is there a way to convert a date time to the following format:
// 11/3/18, 12:00 AM
Date().toString() gives me:
Sat Nov 03 2018 00:00:00 GMT+0000 (UTC)
Thanks.
This is an alternative to format dates, the function Date.prototype.toLocaleDateString allows you to format date according to options/flags.
Some js engines manage the format process differently (so, this is implementation dependent), therefore be careful. Further, you need to check for compatibility in browsers.
let today = new Date();
var options = { year: 'numeric', month: 'numeric', day: 'numeric', hour12: true, hour: 'numeric', minute: 'numeric' };
console.log(today.toLocaleDateString('en-US', options));
tl;dr: try typing this in your browser's javascript console on the moment.js website: moment().format('MM/d/YY h:mm A')
Three things:
1. If you haven't already, check out these date docs for the API:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
(Thorough backgrounder): https://www.toptal.com/software/definitive-guide-to-datetime-manipulation
2. Without an external library
See Ele's answer above for most elegant non-library: https://stackoverflow.com/a/53135859/3191929
Ex. Extract mm/dd/yy from Date
const root = new Date();
let month = root.getMonth(); // 0 to 11
let day = root.getDate(); // 1 to 31
let year = root.getFullYear(); year = String(year).slice(2);
// 11/3/18, 12:00 AM mm/dd/yy, hh:mm AM/PM
const output = ``${month}/${day}/${year}``; // mm/dd/yy
And from there you can explore the API to get the 24 hours, then do a check for AM/PM and build the result etc etc. (see bbram's answer here: https://stackoverflow.com/a/8888498/3191929 for the relevant Date APIs for time)
Here's a quick'n'dirty solution to your specific question
Ex. Extract mm/dd/yy hh:mm AM/PM from Date
function formatDate(root) {
let month = root.getMonth(); // 0 to 11, 0 = Jan
month += 1; // 1 to 12, 1 = Jan
let day = root.getDate(); // 1 to 31
let year = root.getFullYear();
year = String(year).slice(2);
// Time transformation appropriated from bbrame
// https://stackoverflow.com/questions/8888491/how-do-you-display-javascript-datetime-in-12-hour-am-pm-format/8888498#8888498
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
// mm/dd/yy, hh:mm AM/PM
const output = `${month}/${day}/${year} ${formatAMPM(root)}`;
return output;
}
var rootDate = new Date();
console.log(formatDate(rootDate)); // mm/dd/yy hh:mm AM/PM
3. With an external library
Using moment.js you can achieve the above with just this:
var root = moment(); // valid moment date
var formatted = root.format('m/d/YY h:mm A');
See the moment.js docs for more details: https://momentjs.com/docs/#/displaying/format/
If momentjs specifically is a no-go, see here for other options as well: https://github.com/you-dont-need/You-Dont-Need-Momentjs

Convert Epoch time to human readable with specific timezone

To convert epoch dateTime to human readable , using a simple new date(1495159447834) will suffice.
The problem I'm encountering now is that for my hybrid application, if the user set the time-zone in his phone date time setting to lets say GMT +12:00 ,the human readable dateTime will be different from what I would want the user to have and I would want him/her to follow the server timezone.
Thus , how would I convert the epoch number to a specific given timezone in a human readable format.
I have tried example like:
var test= new Date('1495159447834 GMT+0800').toString();
and it returns me an Invalid Date.
If possible, I would want this without any libraries. I have looked through the answers here and I believe that I could not find any answers I'm looking for. If there is any previously answered question with the same topic, do let me know and I will close this question!
You can use offset to convert your current datetime to a specific timezone.
function convertEpochToSpecificTimezone(timeEpoch, offset){
var d = new Date(timeEpoch);
var utc = d.getTime() + (d.getTimezoneOffset() * 60000); //This converts to UTC 00:00
var nd = new Date(utc + (3600000*offset));
return nd.toLocaleString();
}
// convertEpochToSpecificTimezone(1495159447834, +3)
The offset will be your specific timezone. Example: GMT +03:00, your offset is +3. If GMT -10:00, offset is -10
there are number of ways to convert between Epoch and Human readable format
//Convert epoch to human readable date
var myDate = new Date( 1533132667*1000);
document.write(myDate.toGMTString()+"<hr>"+myDate.toLocaleString());
//this will return Wed, 01 Aug 2018 14:11:07 GMT
//Convert human readable dates to epoch
var myDate = new Date("Wed Aug 01 2018 14:11:07 GMT");
var myEpoch = myDate.getTime()/1000.0;
// this will return 1533132667
For Reference: https://www.epochconverter.com/programming/#javascript
Edit#
added a JSFiddle here
This is old, but I did it this way:
function formatDate(date, includeTime) {
const dateTimeFormat = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
timeZone: 'America/Los_Angeles',
timeZoneName: 'short',
});
const [
{ value: month },
,
{ value: day },
,
{ value: year },
,
{ value: hour },
,
{ value: minute },
,
{ value: dayPeriod },
,
{ value: timeZoneName },
] = dateTimeFormat.formatToParts(date);
if (includeTime) {
return `${day} ${month} ${year} • ${hour}:${minute}${dayPeriod.toLowerCase()} ${timeZoneName}`;
}
return `${day} ${month} ${year}`;
This will output the time of the given timezone.
For example, if I have an epoch time (unix timestamp) and if I'm in Argentina, the time should be displayed as 03:45 GMT -3 of June 2, but with this code, it will be displayed as the time that should be displayed for Los Angeles.
My requirement was to display time in Los Angeles timezone, even if I visit the page from Argentina.
set the initial date to the epoch and add UTC units. Say you have a UTC epoch var stored in seconds. How about 1234567890. To convert that to a proper date in the local time zone:
var utcSeconds = 1234567890;
var d = new Date(0); // The 0 there is the key, which sets the date to
the epoch
d.setUTCSeconds(utcSeconds);
Or you can use momentjs
moment.unix(yourUnixEpochTime).format('dddd, MMMM Do, YYYY h:mm:ss A')
or you can use this way
var dateVal ="/Date(1342709595000)/";
var date = new Date(parseFloat(dateVal.substr(6)));
document.write(
(date.getMonth() + 1) + "/" +
date.getDate() + "/" +
date.getFullYear() + " " +
date.getHours() + ":" +
date.getMinutes() + ":" +
date.getSeconds()
);

Javascript clock with variable timezone

I have a clock like so:
const timeContainer = document.querySelector('.timeContainer');
var showTime = (timeZone) => {
let utcTime = new Date().toUTCString();
//need to subtract/add timezone from utcTime
//need to remove everything except for time e.g. 00:22:22
return utcTime;
};
setInterval( () => {
timeContainer.innerHTML = showTime('-8');
}, 1000);
Which gives me GMT time like this:
Tue, 29 Nov 2016 00:35:54 GMT
.. which is what I want! But say I want to get the time in Hong Kong, and also only the numerical time, none of the date and timezone information.
I basically need to:
a) subtract/add a variable timeZone integer from utcTime
b) remove all text in output except for the time, e.g. utcTime only outputs as 00:22:22
I basically need to generate a clock based on what timeZone integer I run showTime with, for example:
showTime(-5);
//returns time in EST timezone
showTime(-6);
//returns time in CST timezone
etc. Is there a way to do this using .toUTCString()? Or is there a better method?
Here's a jsFiddle with my code.
Get the timestamp which is time since the epoch in UTC, offset by the desired timezone and build the string.
const timeContainer = document.querySelector('.timeContainer');
var dateToTimeString = (dt) => {
let hh = ('0' + dt.getUTCHours()).slice(-2);
let mm = ('0' + dt.getUTCMinutes()).slice(-2);
let ss = ('0' + dt.getUTCSeconds()).slice(-2);
return hh + ':' + mm + ':' + ss;
}
var showTime = (timeZone) => {
// convert timezone in hours to milliseconds
let tzTime = new Date(Date.now() + timeZone * 3600000);
return dateToTimeString(tzTime);
};
setInterval( () => {
timeContainer.innerHTML = showTime('-8');
}, 1000);
jsFiddle
Which will output
17:00:00
If you want the time in the "11/29/2016" format you can use toLocaleDateString() instead of toUTCString().
If you want the time in the "Tue Nov 29 2016" format you can use toDateString() instead of toUTCString().

How can I convert string formatted UTC dates without offset to local time in JavaScript?

I am getting a string formatted date with UTC timezone. I need to convert this date time in user's current time zone using jquery or javascript.
I am getting this:
9:43pm 16/10/2015 //this is UTC time, I am getting this via an ajax call
I need to convert it to this:
12:00pm 16/10/2015 //whatever time by that location
If you can pick that format apart, or get a standard format JavaScript can parse - you can convert it to a Date object. I'm not seeing an offset on that date which is problematic when JavaScript tries to parse it. Assuming that is all you have, we can force a UTC date with the following...
// ------- new Date(Date.UTC(year, month, day, hour, minute, second))
var date = new Date(Date.UTC(2015, 9, 16, 21, 43, 0));
console.log(date) // Fri Oct 16 2015 15:43:00 GMT-0600 (Mountain Daylight Time (Mexico))
note that month in Date.UTC is zero based e.g. October would be 9
new Date(value) would do this for us automatically if the format is correct - where value is the actual date value you receive - but that format will not parse as is. If there is no way around that format, you can manipulate it to work in the above example. Here is an untested algorithm for your example...
var formatted = '9:43pm 16/10/2015'
function createDateUTC(formatted) {
var hourOffset = formatted.split(' ')[0].split(':')[1].match(/[a-zA-Z]+/g)[0] === 'pm' ? 12 : 0
var year = parseInt(formatted.split('/').pop());
var month = parseInt(formatted.split('/')[1]) - 1;
var day = parseInt(formatted.split('/')[0].split(' ').pop());
var hour = hourOffset + parseInt(formatted.split(' ')[0].split(':')[0]);
var minute = parseInt(formatted.split(' ')[0].split(':')[1]);
return new Date(Date.UTC(year, month, day, hour, minute, 0));
}
var myDate = createDateUTC(formatted);
JSFiddle Link - working demo
Check out the UTC() and Date Object docs for more info
Additionally, to get the exact format you want, we can introduce some more functions which will give us the 12:00pm 16/10/2015 format
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + '' + ampm;
return strTime;
}
function formatMMDDYYYY(inputFormat) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(inputFormat);
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/');
}
console.log(formatAMPM(myDate) + ' ' + formatMMDDYYYY(myDate));
// Mountain Daylight Time => -- 3:43pm 16/10/2015
JSFiddle Link - formatted example
I'd reccoment looking into Moment.js if you plan to do heavy date formatting and manipulation.
Overall - the best solution to this would be to return an acceptable format from the server, resolve it to local time natively e.g. new Date(), and use a robust formatting library as opposed to rolling your own to display it how you wish.
You should process that string a little bit to extract year, month, day, hour and minute.
Then you can create a local date with that UTC date using this:
var time = new Date ( Date.UTC('year', 'month', 'day', 'hour', 'minute') );
In my case, '9:43pm 16/10/2015' returns: 'Mon Nov 16 2015 07:43:00 GMT-0200 (Hora de verano de Argentina)'.

Categories

Resources