Convert UTC to standard date time format using javascript - javascript

How can I convert a UTC time into proper date - time format using Javascript?
This is what I want to do
var d = new Date("2014-01-01");
var new_d = d.toUTC(); // 1388534400000
var old_d = function(new_d){
// return "2014-01-01" // how can i get this?
}
Now How, can i get orignal date - 2014-01-01 from 1388534400000?
****Also, Please note that when i do this --- new Date(1388534400000); it gives date 1 day less.
That is, instead of giving Jan 01 2014, it gives Dec 31 2013. But, I want Jan 01 2014.****
Is there any method to do the opposite of toUTC() method?
// _________ For those whose toUTC() doesnt work
"toUTC" method works in console of my chrome
See screen shot below

When you pass a string containing hyphens to the Date constructor, it will treat that as UTC. And if you don't pass a time, it will consider it to be midnight. If you are in a time zone that is behind UTC (such as in most of the Americas), you will see the wrong local time conversion.
Here's a screenshot of my chrome dev console, so you can see what I mean
If I pass slashes instead:
Consider using moment.js - which will accept a format parameter that will help you avoid this issue.

Try using the following:
new Date(new_d);

The problem lies with the way you instantiate the Date.
Javascript interpretes the hyphens as an utc date, and slashes as local dates.
Giving the results that mark Explains.
var utcDate = new Date('2014-01-01') // returns a UTC date
var localDate = new Date('2014/01/01'); // Returns local date
But to translate a date back to your starting point string, you can do the following.
function toDateString(utcMillis){
var date = new Date(utcMillis);
d = date.getDate();
m = date.getMonth() +1;
y = date.getFullYear();
return y + '-' + addLeadingZero(m, 2) + '-' + addLeadingZero(d,2);
}
function addLeadingZero(n, length){
n = n+'';
if(n.length<length)
return addLeadingZero('0'+n, length--);
else
return n;
}
If you find yourself with a UTC date, you can still do this:
function toUTCDateString(utcMillis){
var date = new Date(utcMillis);
d = date.getUTCDate();
m = date.getUTCMonth() +1;
y = date.getUTCFullYear();
return y + '-' + addLeadingZero(m, 2) + '-' + addLeadingZero(d,2);
}
To play around with it, and see it for yourself, see this Fiddle:

Related

How to convert a date dd/mm/yyyy into the date object format [duplicate]

I want to convert date to timestamp, my input is 26-02-2012. I used
new Date(myDate).getTime();
It says NaN.. Can any one tell how to convert this?
Split the string into its parts and provide them directly to the Date constructor:
Update:
var myDate = "26-02-2012";
myDate = myDate.split("-");
var newDate = new Date( myDate[2], myDate[1] - 1, myDate[0]);
console.log(newDate.getTime());
Try this function, it uses the Date.parse() method and doesn't require any custom logic:
function toTimestamp(strDate){
var datum = Date.parse(strDate);
return datum/1000;
}
alert(toTimestamp('02/13/2009 23:31:30'));
this refactored code will do it
let toTimestamp = strDate => Date.parse(strDate)
this works on all modern browsers except ie8-
There are two problems here.
First, you can only call getTime on an instance of the date. You need to wrap new Date in brackets or assign it to variable.
Second, you need to pass it a string in a proper format.
Working example:
(new Date("2012-02-26")).getTime();
UPDATE: In case you came here looking for current timestamp
Date.now(); //as suggested by Wilt
or
var date = new Date();
var timestamp = date.getTime();
or simply
new Date().getTime();
/* console.log(new Date().getTime()); */
You need just to reverse your date digit and change - with ,:
new Date(2012,01,26).getTime(); // 02 becomes 01 because getMonth() method returns the month (from 0 to 11)
In your case:
var myDate="26-02-2012";
myDate=myDate.split("-");
new Date(parseInt(myDate[2], 10), parseInt(myDate[1], 10) - 1 , parseInt(myDate[0]), 10).getTime();
P.S. UK locale does not matter here.
To convert (ISO) date to Unix timestamp, I ended up with a timestamp 3 characters longer than needed so my year was somewhere around 50k...
I had to devide it by 1000:
new Date('2012-02-26').getTime() / 1000
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
+ ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now
.getSeconds()) : (now.getSeconds())));
}
For those who wants to have readable timestamp in format of, yyyymmddHHMMSS
> (new Date()).toISOString().replace(/[^\d]/g,'') // "20190220044724404"
> (new Date()).toISOString().replace(/[^\d]/g,'').slice(0, -3) // "20190220044724"
> (new Date()).toISOString().replace(/[^\d]/g,'').slice(0, -9) // "20190220"
Usage example: a backup file extension. /my/path/my.file.js.20190220
Your string isn't in a format that the Date object is specified to handle. You'll have to parse it yourself, use a date parsing library like MomentJS or the older (and not currently maintained, as far as I can tell) DateJS, or massage it into the correct format (e.g., 2012-02-29) before asking Date to parse it.
Why you're getting NaN: When you ask new Date(...) to handle an invalid string, it returns a Date object which is set to an invalid date (new Date("29-02-2012").toString() returns "Invalid date"). Calling getTime() on a date object in this state returns NaN.
JUST A REMINDER
Date.parse("2022-08-04T04:02:10.909Z")
1659585730909
Date.parse(new Date("2022-08-04T04:02:10.909Z"))
1659585730000
/**
* Date to timestamp
* #param string template
* #param string date
* #return string
* #example datetotime("d-m-Y", "26-02-2012") return 1330207200000
*/
function datetotime(template, date){
date = date.split( template[1] );
template = template.split( template[1] );
date = date[ template.indexOf('m') ]
+ "/" + date[ template.indexOf('d') ]
+ "/" + date[ template.indexOf('Y') ];
return (new Date(date).getTime());
}
The below code will convert the current date into the timestamp.
var currentTimeStamp = Date.parse(new Date());
console.log(currentTimeStamp);
The first answer is fine however Using react typescript would complain because of split('')
for me the method tha worked better was.
parseInt((new Date("2021-07-22").getTime() / 1000).toFixed(0))
Happy to help.
In some cases, it appears that some dates are stubborn, that is, even with a date format, like "2022-06-29 15:16:21", you still get null or NaN. I got to resolve mine by including a "T" in the empty space, that is:
const inputDate = "2022-06-29 15:16:21";
const newInputDate = inputDate.replace(" ", "T");
const timeStamp = new Date(newInputDate).getTime();
And this worked fine for me! Cheers!
It should have been in this standard date format YYYY-MM-DD, to use below equation. You may have time along with example: 2020-04-24 16:51:56 or 2020-04-24T16:51:56+05:30. It will work fine but date format should like this YYYY-MM-DD only.
var myDate = "2020-04-24";
var timestamp = +new Date(myDate)
You can use valueOf method
new Date().valueOf()
a picture speaks a thousand words :)
Here I am converting the current date to timestamp and then I take the timestamp and convert it to the current date back, with us showing how to convert date to timestamp and timestamp to date.
The simplest and accurate way would be to add the unary operator before the date
console.log(`Time stamp is: ${Number(+new Date())}`)
Answers have been provided by other developers but in my own way, you can do this on the fly without creating any user defined function as follows:
var timestamp = Date.parse("26-02-2012".split('-').reverse().join('-'));
alert(timestamp); // returns 1330214400000
Simply performing some arithmetic on a Date object will return the timestamp as a number. This is useful for compact notation. I find this is the easiest way to remember, as the method also works for converting numbers cast as string types back to number types.
let d = new Date();
console.log(d, d * 1);
This would do the trick if you need to add time also
new Date('2021-07-22 07:47:05.842442+00').getTime()
This would also work without Time
new Date('2021-07-22 07:47:05.842442+00').getTime()
This would also work but it won't Accept Time
new Date('2021/07/22').getTime()
And Lastly if all did not work use this
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Note for Month it the count starts at 0 so Jan === 0 and Dec === 11
+new Date(myDate)
this should convert myDate to timeStamp

How to add today's time to any date object and getISOString?

I have a ngbDatePicker which helps me to pick a date. Then it returns an object like this:
{year:2020,month:12,day:03}
I'd like to get an ISOString of this date with today's time(current). So if time is 18:42 I should be able to get something like this:
2020-12-03T18:42:00.000Z
To do that I parsed object and made date firstly
(model is the object holds date like above)
var date = new Date(this.model.year + "-" + this.model.month + "-" + this.model.day);
//then to add today's time I found solution below on the internet whcih didn't work for me
var date2 = new Date(date);
var isoDateTime = new Date(date2 .getTime() - (date2 .getTimezoneOffset() * 60000)).toISOString();
Here isoDateTime returns 2020-12-10T03:00:00.000Z which is not I want.
How to solve this?
Working stackblitz
Just take the time part of a Date object and combine it with this.model:
var date2 = new Date();
var date = new Date(this.model.year, this.model.month-1, this.model.day,
date2.getHours(), date2.getMinutes(), date2.getSeconds());
var isoDateTime = date.toISOString();
console.log(isoDateTime);
The month parameter is 0 based, so we have to substract 1 from the month.
Result (I chose Dec.1st 2020 in the Datepicker):
2020-12-01T19:22:42.000Z
Try on Stackblitz
You can create a single Date for the time and append it to values from the object:
function myISOString(obj) {
let z = n=>('0'+n).slice(-2);
return `${obj.year}-${z(obj.month)}-${z(obj.day)}T${new Date().toTimeString().substring(0,8)}`;
}
let obj = {year:2020, month:12, day: 3};
console.log(myISOString(obj));
PS the use of leading zeros like 03 for numbers should be avoided as once upon a time that notation indicated octal values (but not any more), so 09 might be confusing.

How do show my javascript date object in users local time, across various browsers?

I have a project where Im reading JSON data and it contains a date string that Im getting in the following syntax:
2015-09-16T10:00:00
I need to take that string and make it a date object and have it be in the format MM/DD/YYYY hh:mm:ss and make sure its in the viewing users timezone automatically
I have the following function so far, but the issues I see are that
1.) I have to add the 'T' between the date and time in my string or firefox and IE9 tells me NaN and the date object I'm creating ISN'T A VALID DATE. (not sure why, but OK, I can live with adding the 'T')
2.) The bigger issue/problem: Firefox currently has this working and it shows the correct time for my time zone (10:00:00)... but in IE9, chrome and safari, it shows 6:00:00.
Question: How do I get the final output date string to ALWAYS be in the correct time (based on users time zone) across browsers without need of an external library?
Heres the function in its current state:
function cleanDateTime(thisdt) {
var d = new Date(thisdt) // CONVERT THE PASSED STRING TO A DATE OBJECT
var cleanedDate = '';
// GET ALL THE DATE PARTS...
var MM = (d.getMonth()+1).toString();
var DD = d.getDate().toString();
var YYYY = d.getFullYear().toString();
var hh = d.getHours().toString();
var mm = (d.getMinutes()<10?'0':'').toString() + d.getMinutes().toString();
var ss = (d.getSeconds()<10?'0':'').toString() + d.getSeconds().toString();
// BUILD THE FINAL DATE STRING FROM THOSE PARTS...
var cleanedDate = ( MM + '/' + DD + '/' + YYYY + ' ' + hh + ':' + mm + ':' + ss )
return cleanedDate;
};
and I call this function like so...
console.log ( cleanDateTime('2015-09-16T10:00:00') );
** UPDATE / PROBLEM SOLVED ( Thanks achan )...
As suggested, Im now using moment.js and I call the function like so to have it show correct time across browsers:
console.log ( cleanDateTime(moment("2015-09-16T10:00:00")) );
You will have to manually split the datestring and pass the individual parts of the date to the Date constructor and make any timezone adjustments in the process, again, manually. Or use moment.js as achan suggested in the comments.
var ds = '2015-09-16T10:00:00';
var dsSplit = ds.split('T');
var dateArr = dsSplit[0].split('-');
var timeArr = dsSplit[1].split(':');
var yr = dateArr[0], mon = dateArr[1], day = dateArr[2];
var hr = timeArr[0], min = timeArr[1], sec = timeArr[2];
var date = new Date(yr, mon, day, hr, min, sec);
There are a number of issues here. Firstly, never pass strings to the Date constructor because its parsing of strings is unreliable to day the least. The string "2015-09-16T10:00:00" is treated as follows:
In ECMA-262 ed 3 parsing is entirely implementation dependent, early versions of IE will not parse ISO 8601 format dates
In ES5, it will be treated as UTC
In ECMAScript 2015, it will be treated as local (which is also consistent with ISO 8601)
So unless you want to leave it to chance, always manually parse date strings.
Given that you can be sure that the string is a valid date, parsing it per ECMAScript 2015 only requires a couple of lines of code. The following functions create a Date based on either UTC or local time, depending on which you want. Of course it's pretty easy to make them one function with a toggle that looks for a trailing Z and uses UTC.
/** #param {string} s - date string in ISO 8601 format
** #returns {Date} - Date from parsing string as a local date time
**/
function parseISODateLocal(s) {
var b = s.split(/\D/);
return new Date(b[0], b[1]-1, b[2], b[3], b[4], b[5]);
}
document.write(parseISODateLocal('2015-09-16T10:00:00') + '<br>');
/** #param {string} s - date string in ISO 8601 format
** #returns {Date} - Date from parsing string as a UTC date time
**/
function parseISODateUTC(s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0], b[1]-1, b[2], b[3], b[4], b[5]));
}
document.write(parseISODateUTC('2015-09-16T10:00:00'));
Presenting a date as 9/6/2015 10:00:00 on the web is likely to be very confusing for many since the vast majority of the world's population will expect the order to be day, month, year. Far better to use an unambiguous format using the month name like September 6, 2015 or 6-Sep-2015 or similar.
this is how i did mine...
var d, m, day, yr;
d = new Date();
day = d.getDate();
m = d.getMonth();
yr = d.getFullYear();
document.getElementById("dateObj").value = m + "/" + day + "/" + yr;
thanks for your vote..
momentjs.org
this is also my favorite javascript library (underscore)

Timestamp conversion clarification

I created a jsfiddle here
e.onclick=timeConverter('2014-05-02 22:03:34'); //IF I PASS THIS STRING AS DATE, I GOT THIS: 2,May 2014 22:3:34
e.onclick=timeConverter('2014-05-02T22:03:34.890Z'); //IF I PASS THIS STRING AS DATE, I GOT THIS: 3,May 2014 6:3:34
Does "T" or "Z" in the string matters? If someone can enlighten me, thank you.
HTML:
<input type="button" id="format" value="Format Date">
Javascript:
function timeConverter(UNIX_timestamp){
var s = new Date(UNIX_timestamp).getTime()/1000;
var a = new Date(s*1000);
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var year = a.getFullYear();
var month = months[a.getMonth()];
var date = a.getDate();
var hour = a.getHours();
var min = a.getMinutes();
var sec = a.getSeconds();
var time = date+','+month+' '+year+' '+hour+':'+min+':'+sec ;
//var time = date+','+month+' '+year+' '+hour+':'+min+':'+sec ;
alert(time);
}
var e = document.getElementById('format');
e.onclick=timeConverter('2014-05-02 22:03:34');
//e.onclick=timeConverter('2014-05-02T22:03:34.890Z');
Check this document here which is a extract of ISO 8601.
'T' is just meant as separator between Time and Date.
'Z' is a special indicator for UTC (+00:00) as time zone
The Problem is, '2014-05-02 22:03:34' is kinda chrome specific formatting as far as i know, which treats this time as your local time. So the difference of exactly 8 hours appear.
So to be on the safe side, always remember to put the Separator in and keep in mind what timezone you are referring to.
see this wiki-article , the Z in your string means that you are using the
local timezone, so thats the reason for the differnce in your alert
According to ECMA-262, accepted datetime format is:
[+YY]YYYY[-MM[-DD]][THH:mm[:ss[.sss]]]Z
Where Z is either Z or + , - followed by HH:mm. If you specify Z at the end of your timestamp, it means the time is in UTC. Since you are living in GMT+8, your browser adds 8 hours to convert it to local time. Therefore, you get 3,May 2014 6:3:34 instead of 2,May 2014 22:3:34.

UTC Times in JavaScript

I am trying to get the current UTC date to store in my database. My local time is 9:11 p.m. This equates to 1:11 a.m. UTC. When I look in my database, I notice that 1:11 p.m. is getting written to. I'm confused. In order to get the UTC time in JavaScript, I'm using the following code:
var currentDate = new Date();
var utcDate = Date.UTC(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), currentDate.getHours(), currentDate.getMinutes(), currentDate.getSeconds(), currentDate.getMilliseconds());
var result = new Date(utcDate);
What am I doing wrong?
A lttle searching turned out you can do this:
var now = new Date(),
utcDate = new Date(
now.getUTCFullYear(),
now.getUTCMonth(),
now.getUTCDate(),
now.getUTCHours(),
now.getUTCMinutes(),
now.getUTCSeconds()
);
Even shorter:
var utcDate = new Date(new Date().toUTCString().substr(0, 25));
How do you convert a JavaScript date to UTC?
It is a commonly used way, instead of creating a ISO8601 string, to get date and time of UTC out. Because if you use a string, then you'll not be able to use every single native methods of Date(), and some people might use regex for that, which is slower than native ways.
But if you are storing it in some kind of database like localstorage, a ISO8601 string is recommended because it can also save timezone offsets, but in your case every date is turned into UTC, so timezone really does not matter.
If you want the UTC time of a local date object, use the UTC methods to get it. All javascript date objects are local dates.
var date = new Date(); // date object in local timezone
If you want the UTC time, you can try the implementation dependent toUTCString method:
var UTCstring = date.toUTCString();
but I wouldn't trust that. If you want an ISO8601 string (which most databases want) in UTC time then:
var isoDate = date.getUTCFullYear() + '-' +
addZ((date.getUTCMonth()) + 1) + '-' +
addZ(date.getUTCDate()) + 'T' +
addZ(date.getUTCHours()) + ':' +
addZ(date.getUTCMinutes()) + ':' +
addZ(date.getUTCSeconds()) + 'Z';
where the addZ function is:
function addZ(n) {
return (n<10? '0' : '') + n;
}
Modify to suit.
Edit
To adjust a local date object to display the same time as UTC, just add the timezone offset:
function adjustToUTC(d) {
d.setMinutes(d.getMinutes() + d.getTimezoneOffset());
return d;
}
alert(adjustToUTC(new Date())); // shows UTC time but will display local offset
Take care with the above. If you are say UTC+5hrs, then it will return a date object 5 hours earlier but still show "UTC+5"
A function to convert a UTC ISO8601 string to a local date object:
function fromUTCISOString(s) {
var b = s.split(/[-T:\.Z]/i);
var n= new Date(Date.UTC(b[0],b[1]-1,b[2],b[3],b[4],b[5]));
return n;
}
alert(fromUTCISOString('2012-05-21T14:32:12Z')); // local time displayed
var now = new Date();
var utc = new Date(now.getTime() + now.getTimezoneOffset() * 60000);

Categories