convert milisecons to normal date - javascript

function openAPage() {
var startTime = new Date().getTime();
var myWin = window.open("http://www.sabah.com.tr","_blank")
var endTime = new Date().getTime();
var timeTaken = endTime-startTime;
myWin.close()
document.write(startTime);
document.write(endTime);
document.write(timeTaken);
}
hi i want to see the date here "document.write(startTime);".. how can i convert

document.write( new Date(startTime) );
If you check the documentation for the Date object one of the constructors is
new Date(milliseconds)
This way you recreate a Date from the milliseconds passed as argument.
It counts milliseconds since 1 January 1970 00:00:00 UTC.
But keep in mind that the window.open will not wait until the window has loaded before continuing execution of the code. So your startTime and endTime variables will be always pretty close.

Create your startTime with both a time and date and all will be well.
Like this:
var startTime = new Date().getDate();
var myWin = window.open("http://www.sabah.com.tr","_blank")
var endTime = new Date().getDate();
var timeTaken = endTime-startTime;
You can still determine the time difference (elapsed time) between them, but will also have the date available to the end of your routine.
document.write(startTime);
document.write(endTime);
document.write(timeTaken);

Related

node red / JS : calculate time elapsed

I have no experience with JS, but I need to get the time from a node red flow where the payload return the date in this format : 2022-09-03 08:23:39.806170+00:00 and then compare to the sensor.time which is the current date to return the elapsed time.
so something like this VarElapsed to (MyPayload - sensor.time)
again I have no experience with JS so I would thing this would be the result but thatss probably doesn't make any sense...
var d=new Date();
var start_time=payload
d=new Date();
var end_time=d.getTime()
var difference =end_time-start_time;
The format is cool to instantiate a new Date object.
var payload = "2022-09-03 08:23:39.806170+00:00";
var start_time = (new Date(payload)).getTime();
var d = new Date();
var end_time = d.getTime()
var difference = end_time - start_time;
console.log("difference in ms: ", difference)

Nodejs create a date with timzone

I am probably making this harder than I need to.
I am using nodejs on the server. The front-end send me the offset.
I need the UTC equivalent of yesterday (or today, last week...), for example, based on offset.
Currently I have:
getYesterday(): DateRange {
const today = new Date();
const fromDate = format(addDays(today, -1), DATE_SERVER_FORMAT);
const toDate = format(today, DATE_SERVER_FORMAT);
return {
fromDate,
toDate
};
}
But this is all based on the server timezone. I need it based on the offset sent from the frontend.
So today needs to be in UTC. So if the offset is 420 (-7) then Yesterday needs to be '2020-05-19 07:00:00.000' to '2020-05-20 07:00:00.000' even if the server is in Guatamala.
My thoughts are to get today's date (not time) in UTC then add (or subtract) the offset. Then use that date to addDays to.
I'd rather not use an additional library.
Gina
I found the answer here: stackoverflow answer
var d = new Date();
d.setUTCHours(0,0,0,0);
console.log(d.toISOString());
Which allows me to create "yesterday's" date range:
getYesterday(offset :number): DateRange {
var today = new Date();
today.setUTCHours(0,0,0,0);
today = addMinutes(today, offset);
const fromDate = addDays(today, -1).toISOString();
const toDate = today.toISOString();
return {
fromDate,
toDate
};
}
var date1 = new Date();
var date2 = new Date();
console.log(date2.toUTCString());
console.log(date1.getUTCDate());
<h1>Date UTC +_ 0000</h1>
<pre>
You can see the date of output
console.log(date1.getUTCDate());
and
console.log(date2.toUTCString());
is Same
So the simple way to get UTC Date and Time is in built in Date API
</pre>
And to Manage with time difference or what we can say offset Use following script
var targetTime = new Date();
var timeZoneFromClient = -7.00;
var tzDifference = timeZoneFromClient * 60 + targetTime.getTimezoneOffset();
//convert the offset to milliseconds
//add to targetTime
//make a new Date
var offsetTime = new Date(targetTime.getTime() + tzDifference * 60 * 1000);
console.log(offsetTime);

How to compare two datetime with same timezone - jquery

I want to compare two datetime of the same time zone in javascript.
I have tried below code but it's not working due to timezone. I can't get a real local timestamp with timezone.
var createdAt = "2019-07-28T18:14:46+05:30";
var NowTime = new Date($.now());
if(createdAt < NowTime){
$("#sos1").css("background-color","#093");
}else{
$("#sos1").css("background-color","#F03");
}
Convert the datestring to date first using new Date() function
var createdAt = new Date("2019-07-28T18:14:46+05:30");
var NowTime = new Date();
if(createdAt < NowTime){
alert(1);
}else{
alert(2);
}

Fastest method of building a timestamp of the current hour

I'm looking for the fastest method to build a timestamp which represents the current hour starting from the current instant (in general, starting from a timestamp)
Currently I'm doing the following:
var d = new Date();
var year = d.getUTCFullYear();
var month = d.getUTCMonth();
var day = d.getUTCDate();
var hour = d.getUTCHours();
d = new Date(year, month, day, hour);
console.log(d);
console.log(d.getTime());
Is it possible to avoid the second invocation of Date?
If I understand you correctly you want the timestamp of the beginning of the current hour. Then you could simply set the minutes and seconds to 0 in your first Date Object:
var d = new Date();
d.setMinutes(0,0);
console.log(d);
console.log(d.getTime());
You could make it a oneliner, since setMinutes() already returns a timestamp:
var timestamp = new Date().setMinutes(0,0);
Not sure why you're doing that twice, you really don't need to.
var d = new Date();
console.log(d.getHours());
// or
console.log(d.getTime() );

Time between two times on current date

I am trying to calculate the time between two times on the current date using JavaScript. There are other questions similar to this one, but none seem to work, and few with many upvotes that I can find.
I have the following, which fails on the line: var diff = new Date(time1 - time2);, which always gives me an invalid Date when alerted, so it is clearly failing. I cannot work out why.
The initial date is added in the format of: hh:mm:ss in an input field. I am using jQuery.
$(function(){
$('#goTime').click(function(){
var currentDate = new Date();
var dateString = (strpad(currentDate.getDate()) +'-'+ strpad(currentDate.getMonth()+1)+'-'+currentDate.getFullYear()+' '+ $('#starttime').val());
var time1 = new Date(dateString).getTime();
var time2 = new Date().getTime();
var diff = new Date(time1 - time2);
var hours = diff.getHours();
var minutes = diff.getMinutes();
var seconds = diff.getMinutes();
alert(hours + ':' + minutes + ':' + seconds);
});
});
function strpad(val){
return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
}
dateString is equal to: 14-01-2013 23:00
You have the fields in dateString backwards. Swap the year and day fields...
> new Date('14-01-2013 23:00')
Invalid Date
> new Date('2013-01-14 23:00')
Mon Jan 14 2013 23:00:00 GMT-0800 (PST)
dd-MM-yyyy HH:mm is not recognized as a valid time format by new Date(). You have a few options though:
Use slashes instead of dashes: dd/MM/yyyy HH:mm date strings are correctly parsed.
Use ISO date strings: yyyy-MM-dd HH:mm are also recognized.
Build the Date object yourself.
For the second option, since you only really care about the time, you could just split the time string yourself and pass them to Date.setHours(h, m, s):
var timeParts = $('#starttime').val().split(':', 2);
var time1 = new Date();
time1.setHours(timeParts[0], timeParts[1]);
You are experiencing an invalid time in your datestring. time1 is NaN, and so diff will be. It might be better to use this:
var date = new Date();
var match = /^(\d+):(\d+):(\d+)$/.exec($('#starttime').val()); // enforcing format
if (!match)
return alert("Invalid input!"); // abort
date.setHours(parseInt(match[1], 10));
date.setMinutes(parseInt(match[2], 10));
date.setSeconds(parseInt(match[3], 10));
var diff = Date.now() - date;
If you are trying to calculate the time difference between two dates, then you do not need to create a new date object to do that.
var time1 = new Date(dateString).getTime();
var time2 = new Date().getTime();
var diff = time1 - time2;// number of milliseconds
var seconds = diff/1000;
var minutes = seconds/60;
var hours = minutes/60;
Edit: You will want to take into account broofa's answer as well to
make sure your date string is correctly formatted
The getTime function returns the number of milliseconds since Jan 1, 1970. So by subtracting the two values you are left with the number of milliseconds between each date object. If you were to pass that value into the Date constructor, the resulting date object would not be what you are expecting. see getTime

Categories

Resources