Remove Seconds/ Milliseconds from Date convert to ISO String - javascript

I have a date object that I want to
remove the miliseconds/or set to 0
remove the seconds/or set to 0
Convert to ISO string
For example:
var date = new Date();
//Wed Mar 02 2016 16:54:13 GMT-0500 (EST)
var stringDate = moment(date).toISOString();
//2016-03-02T21:54:13.537Z
But what I really want in the end is
stringDate = '2016-03-02T21:54:00.000Z'

There is no need for a library, simply set the seconds and milliseconds to zero and use the built–in toISOString method:
var d = new Date();
d.setSeconds(0,0);
document.write(d.toISOString());
Note: toISOString is not supported by IE 8 and lower, there is a pollyfil on MDN.

While this is easily solvable with plain JavaScript (see RobG's answer), I wanted to show you the Moment.js solution since you tagged your questions as "momentjs":
moment().seconds(0).milliseconds(0).toISOString();
This gives you the current datetime, without seconds or milliseconds.
Working example: http://jsbin.com/bemalapuyi/edit?html,js,output
From the docs: http://momentjs.com/docs/#/get-set/

A non-library regex to do this:
new Date().toISOString().replace(/.\d+Z$/g, "Z");
This would simply trim down the unnecessary part. Rounding isn't expected with this.

A bit late here but now you can:
var date = new Date();
this obj has:
date.setMilliseconds(0);
and
date.setSeconds(0);
then call toISOString() as you do and you will be fine.
No moment or others deps.

Pure javascript solutions to trim off seconds and milliseconds (that is remove, not just set to 0). JSPerf says the second funcion is faster.
function getISOStringWithoutSecsAndMillisecs1(date) {
const dateAndTime = date.toISOString().split('T')
const time = dateAndTime[1].split(':')
return dateAndTime[0]+'T'+time[0]+':'+time[1]
}
console.log(getISOStringWithoutSecsAndMillisecs1(new Date()))
function getISOStringWithoutSecsAndMillisecs2(date) {
const dStr = date.toISOString()
return dStr.substring(0, dStr.indexOf(':', dStr.indexOf(':')+1))
}
console.log(getISOStringWithoutSecsAndMillisecs2(new Date()))

This version works for me (without using an external library):
var now = new Date();
now.setSeconds(0, 0);
var stamp = now.toISOString().replace(/T/, " ").replace(/:00.000Z/, "");
produces strings like
2020-07-25 17:45
If you want local time instead, use this variant:
var now = new Date();
now.setSeconds(0, 0);
var isoNow = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString();
var stamp = isoNow.replace(/T/, " ").replace(/:00.000Z/, "");

Luxon could be your friend
You could set the milliseconds to 0 and then suppress the milliseconds using suppressMilliseconds with Luxon.
DateTime.now().toUTC().set({ millisecond: 0 }).toISO({
suppressMilliseconds: true,
includeOffset: true,
format: 'extended',
}),
leads to e.g.
2022-05-06T14:17:26Z

You can use the startOf() method within moment.js to achieve what you want.
Here's an example:
var date = new Date();
var stringDateFull = moment(date).toISOString();
var stringDateMinuteStart = moment(date).startOf("minute").toISOString();
$("#fullDate").text(stringDateFull);
$("#startOfMinute").text(stringDateMinuteStart);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.js"></script>
<p>Full date: <span id="fullDate"></span></p>
<p>Date with cleared out seconds: <span id="startOfMinute"></span></p>

let date = new Date();
date = new Date(date.getFullYear(), date.getMonth(), date.getDate());
I hope this works!!

To remove the seconds and milliseconds values this works for me:
const date = moment()
// Remove milliseconds
console.log(moment.utc(date).format('YYYY-MM-DDTHH:mm:ss[Z]'))
// Remove seconds and milliseconds
console.log(moment.utc(date).format('YYYY-MM-DDTHH:mm[Z]'))

We can do it using plain JS aswell but working with libraries will help you if you are working with more functionalities/checks.
You can use the moment npm module and remove the milliseconds using the split Fn.
const moment = require('moment')
const currentDate = `${moment().toISOString().split('.')[0]}Z`;
console.log(currentDate)
Refer working example here:
https://repl.it/repls/UnfinishedNormalBlock

In case for no luck just try this code
It is commonly used format in datetime in the SQL and PHP
e.g.
2022-12-25 19:13:55
console.log(new Date().toISOString().replace(/^([^T]+)T([^\.]+)(.+)/, "$1 $2") )

Related

How to add days to javascript unix timestamp? [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

Change format date in JavaScript

I want to change the format in JavaScript, to be Year-month-day
I used this code to get 3 months before, but the format that was generated became like this 9/19/2019.
This my code:
var d = new Date();
d.setMonth(d.getMonth() - 3);
var x = d.toLocaleDateString();
console.log(x);
You can get Year, Month and Date and use string interpolation like below
var d = new Date();
d.setMonth(d.getMonth() - 3);
var formattedDate = `${d.getFullYear()}-${(d.getMonth() + 1)}-${d.getDate()}`;
console.log(formattedDate);
You can use momentjs, a lightweight and handy library for this purpose:
var d = moment(new Date()).subtract(3, 'months').format('dd-MMM-yyyy);
var x = d.toISOString().substring(0,10);
console.log(x);
//it will give you the format of y-m-d
You are using the toLocaleDateString() which will format to the result you received which is expected.
Reference Mozilla's Docs on Date() to get the right function for you there :)
Most instances you are able to just piece it together yourself similar to:
const date = `${date.getYear()}/${date.getMonth()}/${date.getDay()}`;
It's not a nice solution but there are a lot of restrictions with OOTB Date()

Save date 'without' time in JavaScript

At the moment I save my date like this: ISODate("2014-11-17T16:19:16.224Z"), but I want this result: ISODate("2014-11-16T23:00:00Z"). How can I do this?
An easier alternative is to use Date.setHours() - in single call you can set what you need - from hours to milliseconds. If you just want to get rid of the time.
var date = new Date();
date.setHours(0,0,0,0);
console.log ( date );
Set the parts you don't want saved to 0. In your example, you would set the minutes, seconds, and milliseconds to 0.
var date = new Date();
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
var isoDateString = date.toISOString();
console.log(isoDateString);
Or, a less verbose option:
var date = new Date();
var isoDateString = date.toISOString().substring(0,10);
console.log(isoDateString);
To Save a date without a time stamp:
let date = new Date().toLocaleDateString('en-US');
console.log(date)
// OUTPUT -> m/d/yyyy
Use this to find options to add as paramaters for the toLocaleDateString function

convert iso date to milliseconds in javascript

Can I convert iso date to milliseconds?
for example I want to convert this iso
2012-02-10T13:19:11+0000
to milliseconds.
Because I want to compare current date from the created date. And created date is an iso date.
Try this
var date = new Date("11/21/1987 16:00:00"); // some mock date
var milliseconds = date.getTime();
// This will return you the number of milliseconds
// elapsed from January 1, 1970
// if your date is less than that date, the value will be negative
console.log(milliseconds);
EDIT
You've provided an ISO date. It is also accepted by the constructor of the Date object
var myDate = new Date("2012-02-10T13:19:11+0000");
var result = myDate.getTime();
console.log(result);
Edit
The best I've found is to get rid of the offset manually.
var myDate = new Date("2012-02-10T13:19:11+0000");
var offset = myDate.getTimezoneOffset() * 60 * 1000;
var withOffset = myDate.getTime();
var withoutOffset = withOffset - offset;
console.log(withOffset);
console.log(withoutOffset);
Seems working. As far as problems with converting ISO string into the Date object you may refer to the links provided.
EDIT
Fixed the bug with incorrect conversion to milliseconds according to Prasad19sara's comment.
A shorthand of the previous solutions is
var myDate = +new Date("2012-02-10T13:19:11+0000");
It does an on the fly type conversion and directly outputs date in millisecond format.
Another way is also using parse method of Date util which only outputs EPOCH time in milliseconds.
var myDate = Date.parse("2012-02-10T13:19:11+0000");
Another option as of 2017 is to use Date.parse(). MDN's documentation points out, however, that it is unreliable prior to ES5.
var date = new Date(); // today's date and time in ISO format
var myDate = Date.parse(date);
See the fiddle for more details.
Yes, you can do this in a single line
let ms = Date.parse('2019-05-15 07:11:10.673Z');
console.log(ms);//1557904270673
Another possible solution is to compare current date with January 1, 1970, you can get January 1, 1970 by new Date(0);
var date = new Date();
var myDate= date - new Date(0);
Another solution could be to use Number object parser like this:
let result = Number(new Date("2012-02-10T13:19:11+0000"));
let resultWithGetTime = (new Date("2012-02-10T13:19:11+0000")).getTime();
console.log(result);
console.log(resultWithGetTime);
This converts to milliseconds just like getTime() on Date object
var date = new Date()
console.log(" Date in MS last three digit = "+ date.getMilliseconds())
console.log(" MS = "+ Date.now())
Using this we can get date in milliseconds
var date = new Date(date_string);
var milliseconds = date.getTime();
This worked for me!
if wants to convert UTC date to milliseconds
syntax : Date.UTC(year, month, ?day, ?hours, ?min, ?sec, ?milisec);
e.g :
date_in_mili = Date.UTC(2020, 07, 03, 03, 40, 40, 40);
console.log('miliseconds', date_in_mili);
In case if anyone wants to grab only the Time from a ISO Date, following will be helpful. I was searching for that and I couldn't find a question for it. So in case some one sees will be helpful.
let isoDate = '2020-09-28T15:27:15+05:30';
let result = isoDate.match(/\d\d:\d\d/);
console.log(result[0]);
The output will be the only the time from isoDate which is,
15:27

creating date from a timestring in javascript

I am new to javascript and am trying to compare two date values ,I am getting two time value strings in the format
06:30:47 AM
01:10:47 PM
I need to compare these to find out if the first one is less than the other.I couldn't figure out how to do this in javascript.Can someone help?
o.h
I do not think that the standard implementation can parse this. I would do something like this:
function toDate(dateString) {
var timeComponents = dateString.replace(/\s.*$/, '').split(':');
if (dateString.indexOf("PM") > -1) {
timeComponents[0] += 12;
}
var date = new Date();
date.setHours(timeComponents[0]);
date.setMinutes(timeComponents[1]);
date.setSeconds(timeComponents[2]);
return date;
}
if (toDate('06:30:47 AM') > toDate('01:10:47 PM')) {
// ...
}
JavaScript's specified date/time parsing, what you can rely upon cross-browser, is surprisingly limited. For a long time, there was no single string date format that was mandated in the spec, and as of the recent 5th edition spec, the only mandated format is ISO-8601 (and some subsets). You can't yet rely on browsers having implemented that part of the 5th edition spec.
So you have a couple of choices:
Parse the string yourself and use the Date constructor that takes the individual parts of the date as numbers, e.g. new Date(year, month, day, hour, minute, second, ...). (You need only specify as many of those as you want, so for instance new Date(2010, 9, 14) is September 14th, 2010.)
Use a library like Moment that's already done the work for you. Moment lets you specify the format to parse.
Use the Date object. Check this: http://www.w3schools.com/jsref/jsref_obj_date.asp
Try putting the two values in Date variables and do this:
if(var1.valueOf() > var2.valueOf())
{
//Do Something
}
If your times are always in the format 00:00:00 AM then
var a="06:30:47 AM";
var b="01:10:47 PM";
var at=parseInt(a.substring(0,8).replace(/(^0+|:)/g,""));
var bt=parseInt(b.substring(0,8).replace(/(^0+|:)/g,""));
if (a.charAt(9)=="P") {at=at+120000};
if (b.charAt(9)=="P") {bt=bt+120000};
if (at<bt) {
// a is smaller
}
else
{
// a is not smaller
};
..should be cross-browser and time/format safe.
I tried something like this
var ts1="06:30:47 AM";
var ts2="01:10:47 PM";
var ds=new Date().toDateString();
var d1=new Date(ds+" "+ts1);
var d2=new Date(ds+" "+ts2);
if (!(d2>d1)){
alert("d1 should be less than d2");
}
Is there something wrong with this?
// specific formatter for the time format ##:##:## #M
var formatToMiliseconds = function(t){
t = t.split(/[:\s]/);
t = ((t[0] * 3600000) + (t[1] * 60000) * (t[2] * 1000)); // To ms
t = t + (/PM/i.test(t[3]) ? 43200000 : 0); // adjust for AM/PM
return t;
}
var time01 = formatToMiliseconds('06:30:47 AM');
var time02 = formatToMiliseconds('01:10:47 PM');
alert(time01 > time02); // false
allert(time01 < time02); // true
As a bonus, your time is now more compatible with the Date object and other time calculations.

Categories

Resources