Fastest method of building a timestamp of the current hour - javascript

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() );

Related

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);

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

Get time difference in javascript ISO format

I have a datetime in ISO format i.e.
2012-06-26T01:00:44Z
I want to get the time difference from current time. How can I achieve this using javascript or javascript library Date.js or jquery
This will give you the difference in milliseconds, you can then format it as you want
var diff = new Date("2012-06-26T01:00:44Z") - new Date();
Try this:
var someDate = new Date("2012-06-26T01:00:44Z");
var now = new Date();
var one_day = 1000 * 60 * 60 * 24;
var diff = Math.ceil((someDate.getTime()-now .getTime())/(one_day))
alert(diff)
Example fiddle
You can obviously amend the one_day variable to get the difference in the unit you require.
I would suggest converting ISO format to something that works cross browser.
Try this,
var d = "2012-06-26T01:00:44Z";
var someDate = new Date(d.replace(/-/g,'/').replace('T',' ').replace('Z',''));
alert(someDate - new Date());
Edit:
I guess, you need pretty time
Try this awesome code
Edit 2:
You needed reverse, so try this instead
var old_date = new Date();
alert('Old date: ' + old_date.toGMTString())
var new_date = new Date(old_date.setMinutes(old_date.getMinutes() - 5));
alert('Date 5 minutes before: ' + new_date.toGMTString());
If you need timestamp,
alert(new_date.getTime());
in order to format date you can use this function to get the desire format of the date and you can easily change the position of day , month and year.
function convertFormat(inputDate)
var date = new Date(inputDate);
var day = date.getDate();
var month = date.getMonth()+1;
var year = date.getFullYear();
var fullYear = year + '/' + month + '/' + day
return fullYear;

Convert Returned String (YYYYMMDD) to Date

I have a string that contains 8 digits that represent a date. For example:
20120515
I'd like to compare it with today's date, created in this manner:
var currentDate = new Date();
How can I convert the "8 digit date string" to a suitable date format in order to compare it to currentDate?
Use the substring method and substring off 4 elements and assign it to your new date for the year. Then substring off two elements at a time and store the month and date accordingly.
var dateString = "20120515";
var year = dateString.substring(0,4);
var month = dateString.substring(4,6);
var day = dateString.substring(6,8);
var date = new Date(year, month-1, day);
var currentDate = new Date();
Now you can compare the two dates with the normal operators.
If you want a small date library you can use moment.js.
var a = moment("20120515", "YYYYMMDD");
// then use any of moment's manipulation or display functionality
a.format("MMM Do YYYY"); // May 15th 2012
a.fromNow(); // 14 hours ago
a.calendar(); // Today at 12:00 AM
To correctly handle the local time zone, it must explicitly summed to the calculated time
function dateStringToDate(dateString) {
try {
var year = dateString.substring(0, 4);
var month = dateString.substring(4, 6);
var day = dateString.substring(6, 8);
var date = new Date(year, month - 1, day);
const offset = date.getTimezoneOffset()
date = new Date(date.getTime() - (offset * 60 * 1000));
return date;
} catch (error) {
return null;
}
}
function dateStringToDate(dateString) {
try {
var year = dateString.substring(0, 4);
var month = dateString.substring(4, 6);
var day = dateString.substring(6, 8);
var date = new Date(year, month - 1, day);
const offset = date.getTimezoneOffset()
date = new Date(date.getTime() - (offset * 60 * 1000));
return date;
} catch (error) {
return null;
}
}
console.log(dateStringToDate("20211212"))
console.log(dateStringToDate("20211213"))
console.log(dateStringToDate("20211214"))
...some other "one-liner" ways to accomplish this:
(They take a value like dts='20020704'; and return date object [dt].)
var dt=new Date(dts.slice(0,4), (dts[4]+dts[5])-1, dts[6]+dts[7]);
...or...
var m=dts.match(/(....)(..)(..)/), dt=new Date(m[1],m[2]-1,m[3]);
...or...
var m=dts.match(/.{1,2}/g), dt=new Date(m[0]+m[1],m[2]-1,m[3]);
The last one's shortest, but the first is probably most efficient, since it doesn't use regex (but that's irrelevant, unless you're processing LOTS of data using this). I like the middle one best since it's easy to see what's happening.

Javascript validation of date select boxes

I have created 3 select boxes containing days, months and year. What I really would like is to check after the user has selected a date, if the date is over a year from the current date a message is displayed or so.
Im a little stumped on what to do. Any gidance would be great.
Thanks
var ddlYear = document.getElementById('ddlYear');
var ddlMonth = document.getElementById('ddlMonth');
var ddlDay = document.getElementById('ddlDay');
var y = ddlYear[ddlYear.selectedIndex];
var m = ddlMonth[ddlMonth.selectedIndex];
var d = ddlDay[ddlDay.selectedIndex];
// past
var dt = new Date((y+1), (m-1), d);
var moreThanOnYearAgo = dt < new Date();
// future
var dt2 = new Date((y-1), (m-1), d);
var moreThanOnYearAhead = dt2 > new Date();
The y+1 is because if we're adding one year, and are still less than new Date() (today), then it's more than one year ago.
The m-1 is because months in the Date constructor are an enum, which means January is 0.
Don't reinvent the wheel one more time. Use a library that does validation.
There are 31556926000 milliseconds in a year. Just convert that date to a timestamp and subrtact the current date from it. If the result is greater than 31556926000 from it, is over a year away.
var userDate = new Date("11/29/2010");
var now = new Date();
var year_ms = 31556926000;
if ( userDate.getTime() - now.getTime() >= year_ms ) {
// A year away
} else {
// less than a year away
}

Categories

Resources