How to convert a date to string with time zone [duplicate] - javascript

This question already has answers here:
How to ISO 8601 format a Date with Timezone Offset in JavaScript?
(21 answers)
Closed 6 years ago.
In my database I must put a date time in ISO format with time zone. For example I have the following entry column:
17/02/2016 22:00:00 +01:00
I have a web service that accept a date (in JSON object) like this:
{
//...
"Start": "2016-02-17T22:00:00+01:00"
//...
}
Now in my javascript code i've tried:
var today = new Date();
var dateString = today.toISOString();
But the output of dateString is:
"2016-03-05T12:10:32.537Z"
How can I get a string like this:
"2016-03-05T13:10:32.537+01:00"
Thanks

I believe you can't obtain a local ISO 8601 format directly from a Date function. toISOString() gives you the time in UTC / GMT: 2016-03-05T12:10:32.537Z (that's what the Z in the end is for, it means UTC)
This is how you can do it by composing the string yourself:
var date = new Date(); // this is your input date
var offsetHours = -date.getTimezoneOffset() / 60;
var offsetMinutesForDisplay = Math.abs(-date.getTimezoneOffset() % 60);
var offsetHoursForDisplay = Math.floor(offsetHours) + (offsetHours < 0 && offsetMinutesForDisplay != 0 ? 1 : 0);
var isoOffset = (offsetHours >= 0 ? ("+" + fillDigit(offsetHoursForDisplay, true)) : fillDigit(offsetHoursForDisplay, true)) + ':' + fillDigit(offsetMinutesForDisplay, true);
document.getElementById('myDiv').innerHTML = date.getFullYear() + '-' + fillDigit(date.getMonth() + 1, true) + '-' + fillDigit(date.getDate(), true) + 'T' + fillDigit(date.getHours(), true) + ':' + fillDigit(date.getMinutes(), true) + ':' + fillDigit(date.getSeconds(), true) + isoOffset;
function fillDigit(value, withDigit) { // we want to display 04:00 instead of 4:00
if (value >= 0 && value < 10) {
return (withDigit ? "0" : " ") + value;
}
if (value > -10 && value < 0) {
return '-' + (withDigit ? "0" : " ") + (-value);
}
return value;
}
<div id='myDiv'></div>
You can check out http://currentmillis.com/?now for Javascript that will get you multiple formats

If you want a custom format you need format the date by yourself using Date object methods like:
date = new Date();
hour= date.getHours();
min= date.getMinutes();
sec= date.getSeconds();
time= hour+':'+min+':'+sec;
console.log(time)
This can be encapsulated in a function or in a object method for convenience.

Related

Javascript datetime issue - converting to utc

My database value is this
2020-03-08 20:44:00
But in javascript. It display
Mon Mar 09 2020 09:44:00 GMT+0800 (Singapore Standard Time)
Want i want to display on UI
2020-03-08 20:44:00
or
2020-03-08
Is there a way to remove the timezone and get only the actual value from the database.
toISOString is not a proper way to get date into DateTime. please follow the below method to get a date from DateTime.
var date = new Date("2020-03-08 20:44:00");
var year = date.getFullYear();
var month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
var newDate = year + '-' + month + '-' + day;
console.log("Date plush time - "+date);
console.log("Only Date - "+newDate);
You're using the silently using Date object's .toString() method which converts the UTC date (that your database is storing) into a time in the current time zone.
If date is the variable that you get from your database, then you can format it like you want it like this:
let dateString = date.toISOString().replace('T', ' ').replace(/\..+/, '')
This will take your date, convert it into an ISO string (in the form 2020-01-10T03:09:24.551Z) and replace the T with a space and everything after the decimal with nothing.
Try this.
let d = new Date('2020-03-08 20:44:00');
console.log(`${d.getFullYear()}-${d.getMonth() < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1}-${d.getDate() < 10 ? '0' + (d.getDate()): d.getDate()}`);
You can take each part of the date and construct your own format
example:
let formatted_date = my_date.getFullYear() + "-" + (my_date.getMonth() + 1) + "-" + my_date.getDate()
in this example: my_date hold the date you want to display.
If you're able to use a library, use moment.js
https://momentjs.com/docs/#/displaying/
moment("2020-03-08 20:44:00").format("YYYY-MM-DD");
or
moment(new Date("2020-03-08 20:44:00")).format("YYYY-MM-DD");
It can even change the time to utc
https://momentjs.com/guides/#/parsing/local-utc-zone/
moment.utc("2020-03-08 20:44:00").format("YYYY-MM-DD");
hope this helps :)
Subtract your timezone offset milliseconds.
var dt = new Date('2020-03-08 20:44:00');
dt = new Date(dt.getTime()-dt.getTimezoneOffset()*60000);
console.log(dt.toUTCString());
var mo = dt.getUTCMonth()+1, d = dt.getUTCDate(), h = dt.getUTCHours();
var m = dt.getUTCMinutes(), s = dt.getUTCSeconds();
if(mo < 10)mo = '0'+mo;
if(d < 10)d = '0'+d;
if(h < 10)h = '0'+h;
if(m < 10)m = '0'+m;
if(s < 10)s = '0'+s;
console.log(dt.getUTCFullYear()+'-'+mo+'-'+d+' '+h+':'+m+':'+s);

Convert my my variable into a 12/12 time format using moment.js

I need to convert my time that is in military time 24 hours time to regular 12/12 time.
nextArrivalFinal2 = ((hour > 0 ? hour + ":" + (min < 10 ? "0" : "") : "") + min + ":" + (sec < 10 ? "0" : "") + sec);
console.log("nextArrival2", typeof nextArrivalFinal2)
console.log("nextArrival2", nextArrivalFinal2)
var convertedDate = moment(new Date(nextArrivalFinal2));
console.log('converted1', convertedDate)
console.log('converted', moment(convertedDate).format("hh:mm:ss"));
nextArrivalFinal2 displays the time as a string in HH:MM:ss format. But when I plug it into the moment js, it says it is an invalid date.
You are not parsing the time with moment.js, the line:
var convertedDate = moment(new Date(nextArrivalFinal2));
is using the date constructor to parse a string like "13:33:12", which will likely return an invalid date in every implementation (and if it doesn't, it will return something that may be very different to what you expect).
Use moment.js to parse the string and tell it the format, e.g.
var convertedDate = moment(nextArrivalFinal2, 'H:mm:ss'));
Now you can get just the time as:
convertedDate().format('h:mm:ss a');
However, if all you want is 24 hr time reformatted as 12 hour time, you just need a simple function:
// 13:33:12
/* Convert a time string in 24 hour format to
** 12 hour format
** #param {string} time - e.g. 13:33:12
** #returns {sgtring} same time in 12 hour format, e.g. 1:33:12pm
*/
function to12hour(time) {
var b = time.split(':');
return ((b[0]%12) || 12) + ':' + b[1] + ':' + b[2] + (b[0] > 12? 'pm' : 'am');
}
['13:33:12','02:15:21'].forEach(function(time) {
console.log(time + ' => ' + to12hour(time));
});

Date - specific time each day, specific timezone

** UPDATE**
using moment.js would be ok if that would make it easier?
all I'm wanting to do is display a countdown timer that count down to 3pm PST (6EST) daily.
Looking for a way to have javascript get new Date() to use a specific time zome, not the user's time.
I have:
function ShowTime() {
var now = new Date();
var hrs = 14-now.getHours();
var mins = 59-now.getMinutes();
var secs = 59-now.getSeconds();
timeLeft etc etc...
jsfiddle (works) but I think it's my own machine's time:
http://jsfiddle.net/36sqeq8x/
still not working...
I just need to count down to 3pm PST (6EST) daily... without trying to calculate it on users end based on their time zone, like if could calculate from GMT, that would potentially work? but is that even possible.
maybe a combination of something like this?
https://jsfiddle.net/salman/PxzJu/
One way to go about this is to create a Date for the current date and 15:00 in time zone GMT-0800. If that's already passed, add a day to it. If it's more than 1 day in the future (unlikely in a time zone so far west) then subtract a day.
Then subtract the current time from that to get the milliseconds to the next 15:00 PST.
The following makes use of some helper functions, the largest is parseISO to parse an ISO 8601 date string to avoid parsing by the built–in Date parser. toISODate is used to build a string for 15:00 PDT, the others are just for output. Hopefully the documentation and comments is sufficient.
// Create a date for the current date at 15:00 PST (UTC-0800)
// Current date and time
var dLocal = new Date();
// Create Date for same date but time 15:00 at UTC-0800
var dPST = parseISO(toISODate(dLocal) + 'T' + '15:00:00-0800');
// If dPST has passed, add a day
if (dPST < dLocal) dPST.setDate(dPST.getDate() + 1);
// If gap is too big, subtract a day
if (dPST - dLocal > 8.64e7) dPST.setDate(dPST.getDate() - 1);
console.log('Current local: ' + toISOString(dLocal) +
'\nCurrent PST: ' + toISOStringOffset(-480, dLocal) +
'\nNext 3pm PST in PST zone: ' + toISOStringOffset(-480, dPST) +
'\nNext 3pm PST in local zone: ' + toISOString(dPST) +
'\nms to 3pm PST: ' + (dPST - dLocal)
);
/* Parse ISO date string in format yyyy-mm-ddThh:mm:ss.sss+hh:mm or Z
** #param (string} s - string to parse in ISO 8601 extended format
** yyyy-mm-ddThh:mm:ss.sss+/-hh:mm or z
** time zone can omit separator, so +05:30 or +0530
** #returns {Date} - returns a Date object. If any value out of range,
** returns an invalid date.
*/
function parseISO(s) {
// Create base Date object
var date = new Date();
var invalidDate = new Date(NaN);
// Set some defaults
var sign = -1, tzMins = 0;
var tzHr, tzMin;
// Trim leading and trailing whitespace
s = s.replace(/^\s*|\s*$/g,'').toUpperCase();
// Get parts of string and split into numbers
var d = (s.match(/^\d+(-\d+){0,2}/) || [''])[0].split(/\D/);
var t = (s.match(/[\sT]\d+(:\d+){0,2}(\.\d+)?/) || [''])[0].split(/\D/);
var tz = (s.match(/Z|[+\-]\d\d:?\d\d$/) || [''])[0];
// Resolve timezone to minutes, may be Z, +hh:mm or +hhmm
// Splitting into parts makes validation easier
if (tz) {
sign = /^-/.test(tz)? 1 : -1;
tzHr = tz == 'Z'? 0 : tz.substr(1,2);
tzMin = tz == 'Z'? 0 : tz.substr(tz.length - 2, 2)*1;
tzMins = sign * (tzHr*60 + tzMin);
}
// Validation
function isLeap(year){return year % 4 != 0 || year % 100 == 0 && year % 400 != 0}
// Check number of date parts and month is valid
if (d.length > 3 || d[1] < 1 || d[1] > 12) return invalidDate;
// Test day is valid
var monthDays = [,31,28,31,30,31,30,31,31,30,31,30,31];
var monthMax = isLeap(d[0]) && d[1] == 2? 29 : monthDays[d[1]];
if (d[2] < 1 || d[1] > monthMax) return invalidDate;
// Test time parts
if (t.length > 5 || t[1] > 23 || t[2] > 59 || t[3] > 59 || t[4] > 999) return invalidDate;
// Test tz within bounds
if (tzHr > 12 || tzMin > 59) return invalidDate;
// If there's a timezone, use UTC methods, otherwise local
var method = tz? 'UTC' : '';
// Set date values
date['set' + method + 'FullYear'](d[0], (d[1]? d[1]-1 : 0), d[2]||1);
// Set time values - first memeber is '' from separator \s or T
date['set' + method + 'Hours'](t[1] || 0, (+t[2]||0) + tzMins, t[3]||0, t[4]||0);
return date;
}
/* Return ISO 8601 formatted string with local offset, e.g. 2016-06-12T12:43:23.432+05:30
** #param {Date} d - date to craete string from
** #returns {string} in ISO 8601 format with offset
*/
function toISOString(d) {
d = d || new Date();
var offset = d.getTimezoneOffset();
function z(n){return (n<10?'0':'') + n}
// Reverse signe of offset to be consistent with ISO 8601
var offSign = offset < 0? '+' : '-';
offset = Math.abs(offset);
var offHr = z(offset/60 | 0);
var offMin = z(offset%60);
return d.getFullYear() + '-' + z(d.getMonth() + 1) + '-' + z(d.getDate()) + 'T' +
z(d.getHours()) + ':' + z(d.getMinutes()) + ':' + z(d.getSeconds()) + '.' +
('00' + d.getMilliseconds()).slice(-3) + offSign + offHr + ':' + offMin;
}
/* Given a Date, return an ISO 8601 formatted date and time string
** for a particular time zone.
** #param {number} offset - offset in minutes +east, -west, default is local
** #param {Date} d - date to use, default is now
** #returns {string} ISO 8601 formatted string for supplied time zone offset
*/
function toISOStringOffset(offset, d) {
// Copy date if supplied or use now
d = d? new Date(+d) : new Date();
// Prepare offset values
offset = offset || -d.getTimezoneOffset();
var offSign = offset < 0? '-' : '+';
offset = Math.abs(offset);
var offHours = ('0' + (offset/60 | 0)).slice(-2);
var offMins = ('0' + (offset % 60)).slice(-2);
// Apply offset to d
d.setUTCMinutes(d.getUTCMinutes() - offset);
// Return formatted string
return d.getUTCFullYear() +
'-' + ('0' + (d.getUTCMonth()+1)).slice(-2) +
'-' + ('0' + d.getUTCDate()).slice(-2) +
'T' + ('0' + d.getUTCHours()).slice(-2) +
':' + ('0' + d.getUTCMinutes()).slice(-2) +
':' + ('0' + d.getUTCSeconds()).slice(-2) +
'.' + ('000' + d.getUTCMilliseconds()).slice(-3) +
offSign + offHours + ':' + offMins;
}
/* Return an ISO 8601 formatted date string based on local time
** Year must be positive (i.e. doesn't do -ve year)
** #param {Date} date - date object to create date string from
** #returns {string} dates string in yyyy-mm-dd format or default from
** Date.prototype.toString (i.e. "Invalid Date")
*/
function toISODate(date) {
return date.getDate()? ('000' + date.getFullYear()).slice(-4) + '-' +
('0' + (date.getMonth() + 1)).slice(-2) + '-' +
('0' + date.getDate()).slice(-2) : date.toString();
}
The setUTCHours() method sets the hour of a date object, according to the UTC time.
var d = new Date();
d.setUTCHours(15);
Here is the documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCHours
Alternatively, getUTChours return the hour, according to universal time:
var d = new Date();
var n = d.getUTCHours();
Here is the documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCHours
You can use the getUTCHours() and setUTCHours() functions on a date to get/set the hours based on UTC hours instead of local hours. E.g.
var date = new Date();
date.setUTCHours(5);
Or, better, you can use the getTimezoneOffset() function to show the difference and calculate and adjust back to UTC, or which ever timezone you desire. NB the offset is returned in MINUTES.
var date = new Date();
var offset = date.getTimezoneOffset();
console.log(offset);
My output to the above is 300, as I am in CST (strictly speaking, CDT) which is currently 5 hours behind UTC.

Converting to a Date Object from a datetime-local Element

I am using the HTML5 element datetime-local. I need to have two formats of the date. One as a date object the other as a string. I am going to store the date object in the database and I am going to use the string to set the datetime-local form input.
I need to convert this string to a date object:
"2014-06-22T16:01"
I can't seem to get the correct time. This is what I am getting. The time not correct.
Sun Jun 22 2014 09:01:00 GMT-0700 (PDT)
This is the how I am formating the date:
function formatTime(_date) {
var _this = this,
date = (_date) ? _date : new Date(),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear(),
hour = date.getHours(),
minute = date.getMinutes(),
seconds = date.getSeconds(),
function addZero(num) {
return num > 9 ? num : '0' + num;
}
minute = addZero(minute);
seconds = addZero(seconds);
hour = addZero(hour);
day = addZero(day);
month = addZero(month);
return year + '-' + month + '-' + day + 'T' + hour + ':' + minute;
};
Example:
http://codepen.io/zerostyle/pen/gwpuK/
If you are trying to get an ISO 8601 date string, you can try Date.prototype.toISOString. However, it always uses UTC. If you want to include the local timezone, use something like the following:
/* Return a string in ISO 8601 format with current timezone offset
** e.g. 2014-10-02T23:31:03+0800
** d is a Date object, or defaults to current Date if not supplied.
*/
function toLocalISOString(d) {
// Default to now if no date provided
d = d || new Date();
// Pad to two digits with leading zeros
function pad(n){
return (n<10?'0':'') + n;
}
// Pad to three digits with leading zeros
function padd(n){
return (n<100? '0' : '') + pad(n);
}
// Convert offset in mintues to +/-HHMM
// Note change of sign
// e.g. -600 => +1000, +330 => -0530
function minsToHHMM(n){
var sign = n<0? '-' : '+';
n = Math.abs(n);
var hh = pad(n/60 |0);
var mm = pad(n%60);
return sign + hh + mm;
}
var offset = minsToHHMM(d.getTimezoneOffset() * -1);
return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) +
'T' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()) +
'.' + padd(d.getMilliseconds()) + offset;
}
console.log(toLocalISOString(new Date())); // 2014-06-23T07:58:04.773+0800
Edit
The above probably misses your question, which seems to be;
I need to convert this string to a date object: "2014-06-22T16:01"
Presumaly you want to treat it as a local time string. ECMA-262 says that ISO–like strings without a timezone are to be treated as UTC, and that is what your host seems to be doing. So you need a function to create a local Date object from the string:
function parseYMDHM(s) {
var b = s.split(/\D+/);
return new Date(b[0], --b[1], b[2], b[3], b[4], b[5]||0, b[6]||0);
}
console.log(parseYMDHM('2014-06-22T16:01')); // Sun Jun 22 16:01:00 UTC+0800 2014

How to let the return Json(datetime) return millisecondes according to the UTC?

I have a function that retrieves event dates(json format) by ajax. My function should convert the date to a human friendly format. Everything is working but not perfectly. The problem is:
When the server date is
"21/06/2013 22h00" this function returns "22/06/2013 05h00"
"26/07/2013 18h30" this function returns "27/07/2013 01h30"
which is 6 hours of advance.
PS: between my country and the country where my server is located, there is a difference of exactly 6 hours..
Where do I have to put a UTC function?
what's realy wrong with my function?
Thank you
Here is the code:
var jsonifyMyDate = function (jsonDate) {
var parser = parseInt(jsonDate.substr(6));
if (parser > 0 && !isNaN(parser)) {
var newDate = new Date(parser),
_date = newDate.getDate(),
_month = newDate.getMonth() + 1,
_year = newDate.getFullYear(),
_hour = newDate.getHours(),
_minute = newDate.getMinutes();
var dateStr = (_date < 9 ? "0" : "") + _date;
dateStr += "/" + (_month < 9 ? "0" : "") + _month;
dateStr += "/" + _year;
dateStr += " "+(_hour < 9 ? "0" : "") + _hour + "h";
dateStr += (_minute < 9 ? "0" : "") + _minute;
/* + "-" + newDate.getSeconds() + "-" + newDate.getMilliseconds() + "";*/
return dateStr;
} else return "";
UPDATE: I can see the problem with my the server side parsing function within the ActionResult...
So, as I am using Asp.Net+MVC(C#), How to let the
return Json(datetime);
return UTC millisecondes instead of the server's one ?
Json formate is created based on UTC datetime.
After getting the datetime from ajax call, you have to convert this UTC datetime in to local datetime zone.
Ex:
var date = new Date('6/29/2011 4:52:48 PM UTC');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"

Categories

Resources