Can't convert timestamp to date properly in Javascript - javascript

I use mongodb as my database and in that db I have a timestamp field but I haven't seen any format similar to that. Some of them are:
1657479170.7300725
1657479170.7301126
1657479170.7301197
1657479170.9120467
1657479170.932398
When i try to convert this to normal date format (YYYY-MM-DD) I get the correct date. For example the converted date of the first timestamp above is:
10.07.2022 21:52:50
However when I try to convert it in javascript I get:
1970-01-20 06:24:39
which is definitely not correct value.
My code for the conversion :
ConvH.forEach(conv => {
conv.tracker.events.forEach(element => {
console.log(parseFloat( parseFloat(element.timestamp.toFixed(4))), moment(new Date( parseFloat( element.timestamp.toFixed(4)))).format("YYYY-MM-DD HH:mm:ss"));
element.timestamp = new Date(element.timestamp).toLocaleString();
})
});
Note : new Date(element.timestamp).toLocaleString(); gives the same thing :/

Try this: new Date(timestamp.getHighBits() * 1000)

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

ERROR Error: InvalidPipeArgument: "12-01-2020 - 12-02-2020' to a date' for pipe 'DatePipe'

I am trying to concatenate two dates and assigning to variable but it is throwing an error
ERROR Error: InvalidPipeArgument: 'Unable to convert “12-01-2020 - 13-02-2020” into a date' for pipe 'DatePipe'.where I am going wrong?
dates which I am getting from backend is projectStartDate: "2020-12-21T13:55:00.000+00:00".I am converting it to 12-01-2020 / timestamp after that concatenating both and assigning to projectduration value.
this.startDate = this.datepipe.transform(response.projectStartDate, 'yyyy-MM-dd','es-ES');
this.endDate = this.datepipe.transform(response.projectEndDate, 'yyyy-MM-dd','es-ES');
response.gbRFEbean.projectDuration.value = this.startDate + "-" +this.endDate ;
The Date format: DD-MM-YYYY is invalid.
You can try using :
new Date("12-01-2020")
It will give Invalid Date in chrome dev tools.
Solution
You can change the date format to MM-DD-YYYY and then pass it to datepipe.transform
let date = response.projectStartDate.replace(/(\d{2})-(\d{2})-(\d{4})/, "$2-$1-$3")
this.startDate = this.datepipe.transform(date, 'yyyy-MM-dd','es-ES');
date = response.projectEndDate.replace(/(\d{2})-(\d{2})-(\d{4})/, "$2-$1-$3")
this.endDate = this.datepipe.transform(date , 'yyyy-MM-dd','es-ES');
locale is the fourth argument of the DatePipe transform and timezone is the third argument. Currently you have the locale as the third argument. I'd probably configure your locale like this (and the date pipe will automatically work for your locale without specifying):
Missing locale data for the locale "XXX" with angular
transform takes either a javascript date or an ISO date string so I'm guessing your dates (projectStartDate, projectEndDate) are strings that aren't in the ISO format? The error message implies that one of those fields has the entire value of 12-01-2020 - 13-02-2020
sample code with ISO date string
startDate = '2020-01-12';
endDate = '2020-02-13';
formattedStartDate = this.datePipe.transform(this.startDate);
formattedEndDate = this.datePipe.transform(this.endDate);
constructor(private datePipe: DatePipe) {
console.log(`${this.formattedStartDate} - ${this.formattedEndDate}`);
}
Sample code with javascript date
startDate = new Date('2020-01-12');
endDate = new Date('2020-02-13');
formattedStartDate = this.datePipe.transform(this.startDate, 'yyyy-MM-dd');
formattedEndDate = this.datePipe.transform(this.endDate, 'yyyy-MM-dd');
constructor(private datePipe: DatePipe) {
console.log(`${this.formattedStartDate} - ${this.formattedEndDate}`);
}
If your dates are strings in a dd-MM-yyyy format, you can parse them with a library like luxon:
npm i luxon
And import
import { DateTime } from 'luxon';
And parse
startDate = DateTime.fromFormat("12-01-2020", "dd-MM-yyyy").toISODate();
As a final note it's a little funny to put the dates in an ISO date format (yyyy-MM-dd) and then format them in the same format. The pipe makes more sense, particularly with you app locale set, if you want to use formats such as mediumDate (the default) which might display 12 ene. 2020

Convert given timestamp to influxdb timestamp

My Incoming Date is in format : 15.08.2017 23:03:23.120000
Here I am using Node-Red Platform to convert msg.payload.time in Influx timestamp but I am getting this Error:
"Error: Expected numeric value for, timestamp, but got '15.08.2017 23:03:23.120000'!".
Please let me know the script for given timestamp to influxdb timestamp.
InfluxDB expects unix timestamps and msg.payload.time might be a string, hence you are getting the error.
In order to generate a timeStamp from a date, you can use the Date functionality of JS.
It works in the following way:
new Date('<your-date-string>').valueOf()
Here the date-string is expected in 'YYYY-MM-DD hh:mm:ssZ' format.
In your case, since the msg.payload.time is available in dd.mm.yy hh:mm:ssZ format, you will need to perform some additional operations.
You can update your code as below:
const incomingDate = msg.payload.time;
// extract the date dd.mm.yyyy from the incoming Date String
const splittedDate = incomingDate.split(' ');
// Convert the date from dd.mm.yyyy to yyyy-mm-dd format
let date = splittedDate[0].split('.').reverse().join('-');
// Store time value in a separate variable for later use.
const time = splittedDate[1];
// merge date and time to form yyyy-mm-dd hh:mm:ssZ format
const datetime = `${date} ${time}`
// assign the timestamp value to fields.time
fields.time = new Date(datetime).valueOf();
Here is a working example
const incomingDate = '15.08.2017 23:03:23.120000';
const splittedDate = incomingDate.split(' ');
let date = splittedDate[0].split('.').reverse().join('-');
const time = splittedDate[1];
const datetime = `${date} ${time}`
console.log(datetime);
console.log(new Date(datetime).valueOf())

Parsing datetime with Z and T in javascript

I'm currently using an API that's returning a timestamp in a weird format that I'm struggling to parse into a unix timestamp for my database, the result I'm receiving is:
"date": "20190412T131518.000Z",
I've tried using:
var date = new Date(array.date);
console.log(date.parse);
Which just returns NaN so I'm unsure where to go with it
You could add some dashes and colons.
20190412T131518.000Z // input
2019-04-12T13:15:18.000Z // needed format
It looks like, that Date does not fully accept date string in ISO 8601 format. It respects only a version from the standard in the form
YYYY-MM-DDTHH:mm:ss.sssZ
var string = "20190412T131518.000Z",
date = new Date(string.replace(/(....)(..)(.....)(..)(.*)/, '$1-$2-$3:$4:$5'));
console.log(date);
You can parse from the string to the Date object as below:
let rawDate = "20190412T131518.000Z";
let myDate = new Date(Date.UTC(
rawDate.substr(0, 4),
rawDate.substr(4, 2),
rawDate.substr(6, 2),
rawDate.substr(9, 2),
rawDate.substr(11, 2),
rawDate.substr(13, 2)
));
console.log(myDate);

Javascript - Convert ####-##-## to Epoch time

Is there a way to take a date object from a HTML object in the format of ####-##-## and convert it to epoch time. For example, the user inputs the value of August 12, 2012 which shows as 2012-08-12 when I print out the .val() of it, and I need to get this in Epoch time.
EDIT
Code to date:
if (hvStartDate == "") {
hvStartDate = "start"
}
else {
console.log($("#hv-start-date").val()); // => 2012-08-20
hvStartDate = new Date($("#hv-start-date").val()).getTime(); // => NaN
}
if (hvEndDate == "") {
hvEndDate = "end"
}
else {
hvEndDate = new Date($("#hv-end-date").val()).getTime(); // => NaN
}
var myTmp = new Date("2012-08-20");
console.log(myTmp.getTime()); // => NaN
Javascript's Date built-in allows you to pass a date string into its constructor, giving you a Date based on that string. From there, calling getTime( ) will give you the epoch time.
new Date($('.user-value').val()).getTime(); // => epoch time
new Date('2012-08-12').getTime(); // 1344729600000
Caveat: Beware of locale strings and locale-specific date formatting (for example, the position of days and months switch depending on locale).
EDIT: Based on your code in the comment below, here's what you need to do. Notice that you have to instantiate a new Date Object before calling getTime():
if (hvStartDate == "") {
hvStartDate = "start"
}
else {
hvStartDate = new Date($("#hv-start-date").val()).getTime();
}
Simply use the getTime() function. It returns the number of milliseconds since Epoch :
var msSinceEpoch = myDate.getTime();
Complete Date reference at MDN : https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
EDIT : if you have to parse it too, you may :
use new Date(theString) if it has the good format
set yourself the different date fields (see reference) after having parsed it
use a date parsing library. I use this one : http://www.datejs.com/ which is very powerful for all date parsing, computing and formating.

Categories

Resources