How to add days to javascript unix timestamp? [duplicate] - javascript

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

Related

How to convert a date to ISO format but with timezone info in place of the 'Z' in Javascript?

I have always worked with dates in ISO format that ends with a 'Z'. But now I have to replace that 'Z' with timezone info like +08:00.
In other words, currently I have this format 2020-01-17T00:30:00.000Z, but now I need it in this format 2020-01-17T08:30:00+08:00.
Looks like popular date library like moment and dayjs convert date to ISO format without 'Z' too by default. Is that still considered an 'ISO' date format? And I can't find out how to do it with vanilla Javascript and doing the .toISOString() always gives me the 'Z'..
If you get the date string in the ISO format, but you want to get the string in a certain timezone, with the timezone.
Then here's a simple function that does just that.
function getISODateStampWithTZ (date, tzHours)
{
let dateTz = new Date(date);
dateTz.setUTCHours(tzHours);
return dateTz.toISOString().replace(/Z$/,
(tzHours<0 ? '-' : '+') +
(Math.abs(tzHours)<10 ? '0'+Math.abs(tzHours) : Math.abs(tzHours)) +
':00');
}
const date = new Date('2020-01-17T00:30:00.000Z');
console.log(date.toISOString());
console.log(getISODateStampWithTZ(date, 8));
console.log(getISODateStampWithTZ(date, -1));
Such function could also be added to the Date prototype.
The example below prefixes the function with 'custom' to make it distinct from standard methods.
Date.prototype.customToISOStringTZ = function (tzHours)
{
let dateTz = new Date(this);
dateTz.setUTCHours(tzHours);
return dateTz.toISOString().replace(/Z$/,
(tzHours<0 ? '-' : '+') +
(Math.abs(tzHours)<10 ? '0'+Math.abs(tzHours) : Math.abs(tzHours)) +
':00');
}
const date = new Date('2020-01-17T00:30:00.000Z');
console.log(date.toISOString());
console.log(date.customToISOStringTZ(8));
console.log(date.customToISOStringTZ(-1));
parser.isoparse('2019-08-28T14:34:25.518993Z')
use this to get correct format
The Z ("Zulu") on the end means UTC, ie. an offset from UTC of zero. I'm assuming you want to convert from UTC to local time, in which case you need to calculate the offset from UTC:
function convertUTCDateToLocalDate(date) {
const newDate = new Date(date.getTime() + date.getTimezoneOffset() * 60 * 1000);
const offset = date.getTimezoneOffset() / 60;
const hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
Usage:
const date = new Date("2020-01-17T00:30:00.000Z")
const newDate = convertUTCDateToLocalDate(date)
newDate.toISOString() // "2020-01-17T01:30:00.000+01:00"
Beware! This solution won't work for timezones where the offset isn't a full hour.
If you're running this in a browser I'd strongly recommend using a tool like moment.

What is the difference in these timestamps?

So I am trying to make a post request to an API, and one of the values required is a date that according to there documentation should be in the following format
Start time of the timesheet, in ISO 8601 format
(YYYY-MM-DDThh:mm:ss±hh:mm). Time should reflect the user's local time.
But when I try to make a new Date().toISOString() value in the ISO format I get this
2019-07-17T19:50:08.057Z
So I guess my question is, how can I produce the supposed format that they are looking for which is apparently a different ISO 8601 format? Or what would be the format for the following timestamp?
2018-07-25T13:10:23-07:00
here is the documentation to the api that I am playing around with https://tsheetsteam.github.io/api_docs/#create-timesheets
Your question is similar to Javascript date format like ISO but local but you want the timezone also, so:
function toISOLocal(date) {
// Pad single digit numbers with leading zero
function z(n){return (n<10?'0':'')+n}
// Copy the input date
var d = new Date(date);
// Get offset and adjust
var offset = d.getTimezoneOffset();
d.setMinutes(d.getMinutes() - offset);
// Build timestamp with adjusted date and local offset
var sign = offset < 0? '+' : '-';
offset = Math.abs(offset);
var offsetStr = sign + z(offset/60|0) + ':' + z(offset%60);
return d.toISOString().replace(/z$/i, offsetStr);
}
console.log(toISOLocal(new Date()));
However I suspect you can get by with the built–in toISOString and just replace the trailing Z with +00:00. You might need to remove the decimal seconds part also:
function modifyISO(d) {
return d.toISOString().replace(/\.\d+/, '').replace(/z$/i,'+00:00');
}
console.log(modifyISO(new Date()));
Just remove the tail. Something like this.
console.log(new Date().toISOString().replace(/(.+)(\..+?$)/g,'$1'));
You need set location time to make reference to meridian 0 + or - , you can set with library like momentjs, basically you set a reference to compare
var newYork = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london = newYork.clone().tz("Europe/London");
newYork.format(); // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format(); // 2014-06-01T17:00:00+01:00

Convert a AM/PM date string to JavaScript date using jQuery

I have a date string like this 20/09/2018 12:00 AM. I need to stop to put the previous date than today. I have searched the web for it, but no answer found with this format.
I need the default date format of JavaScript so that I can compare with new Date() value. When I use the following format it show the message that says invalid date because of my dd/MM/yyyy hh:mm tt format.
alert(new Date("20/09/2018 12:00 AM"));
Igor recommended using moment.js to solve this — it is a widely used date/time library.
With moment.js you can do this:
var m = moment("20/09/2018 3:14 PM", "DD/MM/YYYY h:mm a");
var d = m.toDate();
The first line creates a "moment" object by parsing the date according to the format string specified as the second argument. See http://momentjs.com/docs/#/parsing/
The second line gets the native javascript Date object that the moment object encapsulates; however, moment can do so many things you may not need to get back that native object.
See the moment docs.
Your format isn't valid, thus you're getting invalid date error. So, using your format(dd/MM/yyyy hh:mm tt) we'll grab the year, month, day, hours and the minutes, then we'll reformat it as an acceptable format by the Date constructor and create a Date instance.
Here's a function that do all what being said and returns a Date instance which you can compare it with another Date instance:
function convertToDate(str) {
// replace '/' with '-'
str = str.replace(/\//ig, '-');
/**
* extracting the year, month, day, hours and minutes.
* the month, day and hours can be 1 or 2 digits(the leading zero is optional).
* i.e: '4/3/2022 2:18 AM' is the same as '04/03/2022 02:18 AM' => Notice the absence of the leading zero.
**/
var y = /\-([\d]{4})/.exec(str)[1],
m = /\-([\d]{2}|[\d])/.exec(str)[1],
d = /([\d]{2}|[\d])\-/.exec(str)[1],
H = /\s([\d]{2}|[\d]):/.exec(str)[1],
i = /:([\d]{2})/.exec(str)[1],
AMorPM = /(AM|PM)/.exec(str)[1];
// return a Date instance.
return new Date(y + '-' + m + '-' + d + ' ' + H + ':' + i + ' ' + AMorPM)
}
// testing...
var str1 = '20/09/2018 12:00 AM';
var str2 = '8/2/2018 9:00 PM'; // leading zero is omitted.
console.log(convertToDate(str1));
console.log(convertToDate(str2));
The Date depends on the user's/server's location, two users may have
different results.
Learn more
about Date.
Hope I pushed you further.

Why new date() is not accepting string and give invalid date?

Javascript:I have a function which has s parameter s contains this s=07:05:45PM;s has time which is in form of string i want to use it in new Date() but gives error i had to get hours mins seconds convert this time to 24 hour format please help me output:invalid date
function time Conversion(s) {
var date=new Date(s);
console.log(date);
}
According to specification, you can pass the dateString as a parameter to the Date constructor. There is a bunch of dateString format limitations, and in you case your dateString (named s) is invalid for date constructor (actually, your s is even has not any date, it consists of time only).
The possible solution is to handle your s parameter manually: cut verbal part, split time by :, then pass params to the Date constructor in sequence year, month, date, hours, minutes, seconds, or construct your own ISO String, format:
{year}-{month}-{date}T{hours}:{minutes}:{seconds}.{milliseconds}Z
Note, that hours in both cases should be in 24-hours format, so you should manually handle your 12-h formatted hours.
The reason you're getting an invalid Date from the built-in parser is covered by Why does Date.parse give incorrect results?
To convert a string like 07:05:45PM to 24 hour time, you can parse the parts and generate an new string, adding 12 to the hour if it ends in PM or not if it ends in AM (and change 12am to 00). e.g.
function to24HrFormat(s) {
var z = n => (n<10?'0':'')+n;
var b = s.match(/\d+/g);
var ap = /am$/i.test(s)? 0 : 12;
return z((b[0]%12) + ap) + ':' + b[1] + ':' + b[2];
}
// Tests
['07:05:45PM', '06:23:49AM', '12:15:00AM', '11:59:59pm']
.forEach(s => console.log(s + ' => ' + to24HrFormat(s)));
You should validate the input string, and maybe allow for missing seconds.
From the time string, remove the AM/PM (need to have a 24hr timestring)
var time = "07:05:45";
var datetime = new Date('1970-01-01T' + time + 'Z');
Now do your time based operations.
Try using Date.parse(string) instead. See referene.

JavaScript convert DateTime:"2017:10:01 19:06:57" string to ISO date string

I need to convert the following
DateTime:"2017:10:01 19:06:57"
To ISO date/time format I tried doing to image.exif.DateTime.toISOString()
But ran into an error, am I missing something?
You have to replace the first two colons by dashes. You can achieve that by .replace(/:(?=.* )/g, '-'), which in that case has the same effect as .replace(':', '-').replace(':', '-').
Additionally you have to replace the space by the letter T.
var dateString = "2017:10:01 19:06:57";
var dateStringISO = dateString.replace(/:(?=.* )/g, '-').replace(' ', 'T');
// (timezone indicator is optional)
console.log(dateStringISO); // That format fulfills ISO 8601.
var date = new Date(dateString.replace(/:(?=.* )/g, '-'));
// here you could manipulate your date
console.log(date.toISOString());
If, your browser doesn't support toISOString() method. try below code
function ISODate(d) {
function pad(n) {return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
var d = new Date();
console.log(ISODate(d));
It is unlikely that any JS implementation will understand the format:
2017:10:01 19:06:57
Eg. in Chrome's dev tools:
08:28:08.649 new Date("2017:10:01 19:06:57")
08:28:08.649 Invalid Date
(Colons are typically time separators and no element of a time can be 2017.)
Therefore you're going to need to parse it yourself. Something like:
var year = parseInt(str.substring(0, 4));
var month = parseInt(str.substring(5, 7));
// etc for day, hour, min, sec
var d = new Date(year, month, day, hour, min, sec);
(This will create to a local time, if you want UTC then use Date.UTC rather than the constructor.)

Categories

Resources