Getting incorrect dates converting timestamp with new Date - javascript

I'm trying to convert timestamp to Date but I'm getting incorrect dates. I'm working on a project with Angular and Typescript.
I have timestamps like:
1451642400 (1st january 2016) and 1454320800 (1st february 2016)
If I code:
date = new Date(1451642400);
console.log(date.toLocaleString());
date = new Date(1454320800);
console.log(date.toLocaleString());
I get:
17/1/1970 20:14:02 and 17/1/1970 20:58:40
when I should get:
1/1/2016 10:00:00 and 1/2/2016 10:00:00
What's the problem? How can I fix it?

You need to multiply your Unix Timestamp by 1000 so its in milliseconds..
If you do it like this, it will work:
date = new Date(1451642400 * 1000);
console.log(date.toLocaleString());
date = new Date(1454320800 * 1000);
console.log(date.toLocaleString());

The new Date()'s argument is in miliseconds. So try your timestamps with 1000 to make it in miliseconds.
var date = new Date(1451642400 * 1000);

Related

How to convert UNIX timestamp into relative date like whatsapp last seen status with moment.JS

I would like to show a UNIX timestamp into last seen status same as what WhatsApp does in javascript. I am using moment.js and as far as I know, we can format the date or can use .fromNow() which gives a relative date but not what I am looking for.
For example,
Lets the Unix timestamp : 1606908420
If I use moment.unix(1606908420).formNow() the result will be few seconds ago or something similar
But what I am looking for is, it should show Today 11:30 am.
Likewise
For a date of yesterday, it should show: Yesterday 11:30 am
For a date of day before yesterday, it should show: Mon 11:30 am
Any date of last week or earlier, it should show 25-11-2020
Can anyone please help me how can I achieve this?
Convert UNIX timestamp into date
using toDate() method
{new Date(timestamp?.toDate()).toUTCString()}
Wed, 2 Dec 2020 12:00:00 GMT
using moment method
{moment.unix(order.data.created).format("MMMM Do YYYY, h:mma")}
I highly recommend the second one moment for you. learn more from
moment docs
Convert Moment Date to looks like In Whatsapp
//utility function to convert your date to looks like in whatsapp
const dateFormatter = (date) => {
//here we were subtracting our date from current time which will be in milliseconds
const dateDifferenceInTime =
new Date().getTime() - new Date(date.toDate()).getTime();
// conerting milli seconds to days
// (1000 milliseconds * (60 seconds * 60 minutes) * 24 hours)
const dateDifferenceInDays =
dateDifferenceInTime / (1000 * 60 * 60 * 24);
//After returning in particular formats as of our convinent
if (dateDifferenceInDays < 1) {
return moment(date.toDate()).format("LT");// 10:04 am
} else if (dateDifferenceInDays < 2) {
return "Yesterday"; // just YesterDay
} else if (dateDifferenceInDays <= 7) {
return moment(date.toDate()).format("dddd");//like monday , tuesday , wednesday ....
} else {
return moment(date.toDate()).format("l");// if it was more than a week before it will returns as like 05/23/2022
}
};

Stop date to epoch conversion in javascript

I have a code where I try to set date 20 days back from current date on server. I have used a variable(say dateRange) in javascript to get current date. But on using the same variable second time for setDate() function value of dateRange is changed to epoch from date. I know I can convert epoch to date and proceed but is there a way to stop this automatic conversion.
var dateRange=new Date(currentDate);
dateRange = dateRange.setDate(dateRange.getDate() - 20);
setDate modifies the date object, and returns the epoch value. Just don't save the epoch value in dateRange, so you can use the date object after modifying it:
var currentDate = new Date();
var dateRange = new Date(+currentDate);
console.log(dateRange.toISOString());
dateRange.setDate(dateRange.getDate() - 20);
console.log(dateRange.toISOString());
Side note: Copying a date by doing var dateRange = new Date(currentDate); is/was unreliable on some browsers. In the above, I've changed it to var dateRange = new Date(+currentDate); (note the +, converting the date to its epoch value), which is reliable.
Internally dates are stored as milliseconds from the epoch date.
To achieve what you are trying to do you can subtract the number of milliseconds that corresponds to 20 days:
var currentDate = "2019-07-29T07:14:57.269Z";
var dateRange = new Date(currentDate);
var pastDate = new Date(dateRange - 1000 * 60 * 60 * 24 * 20);
console.log('current', currentDate);
console.log('20 days ago', pastDate);
anyway if you are doing a lot of date/time manipulations in your app i suggest you to use this library: https://momentjs.com/

moment.js timezone get milliseconds

I'm trying to get number of days passed. I'm storing epoch (milliseconds) for date.
I'm reading startDate from database (date value of first record) in milliseconds and I want to find current epoch in specified timezone.
I tried this:
var startDate = rows[0]['MIN_DATE'];
var endDate = moment().tz("America/New_York");
Then to calculate difference, I used:
var oneDay = 24 * 60 * 60 * 1000;
var daysCount = Math.ceil((endDate - startDate) / (oneDay));
The value of startDate is:
1522821600000 which is: Wednesday, April 4, 2018 2:00:00 AM GMT-04:00 DST
The value of endDate is:
Moment_d: Wed Apr 04 2018 22:24:45 GMT-0400 (EDT)_isAMomentObject: true_isUTC: true_isValid: true_locale: Locale_offset: -240_pf: Object_z: Zone__proto__: Object
The value of daysCount is 2, how?
How can I get milliseconds instead of object from:
moment().tz("America/New_York");
To directly answer your question, use .valueOf() to get the value of moment.tz("America/New_York")
var endDate = moment.tz("America/New_York").valueOf()
I'm having difficulty understanding your question, but I believe you're trying to get the difference between the days considering the correct timezone. The following gives an accurate result using .diff() (https://momentjs.com/docs/#/displaying/difference/)
var timeZone = "America/New_York"
var startDate = 1522821600000
var momentStartDate = moment.tz(startDate,timeZone)
var momentEndDate = moment.tz(timeZone)
alert(momentEndDate.diff(momentStartDate, 'days') );
Use fromNow() function. It is very straight-forward.
Do like this :
moment(date).fromNow();
It will give you number of days passed if date is past as well as number of days to go if date is future.
Below are is example:
var date = 1522821600000; // your date
console.log(moment(date).fromNow());
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
Solved this with following statement:
var endDate = moment().tz("America/New_York").valueOf();

how to add time plus and recalculate the datetime

i have this datetime format:
Oct 31, 2012 08:59:52
i would like to re-calculate the datetime incremented (for example) of 2 hours or 50 minutes plus how can i do that?
i need to return the same datetime format showed above and not a timestamp!
var date = new Date("Oct 31, 2012 08:59:52");
var timeInMillis = date.getTime();
Now that you have time in milliseconds, you can just add the time you want in millis.
Eg: 2 hours? So, 2*60*60*1000 + timeInMillis
var newDate = new Date(2*60*60*1000 + timeInMillis);
If you want to convert your newDate into the original format, which is a long process, you can some guidance from here:
Where can I find documentation on formatting a date in JavaScript?
My pick of the answers would be:
Use MomentJS
You could first parse this to a date:
var d=new Date("October 31, 2012 08:59:25").getTime();
Then add the offset:
d+= (seconds)*1000 + (minutes)*60000 + (hours)*3600000;
var result = new Date(d);
I am just not sure wether it accepts 'Oct' instead of 'October'
time_start = new Date(year, month, day, hours, minutes, seconds, milliseconds);
time_finish = new Date() - time_start;
Set the Date using the format listed above. To calculate the interval between two points of time, just subtract the current date from the past date.

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

Categories

Resources