how can I get the ms of the day at midnight with vanilla js ; something like this:
const today = new Date().setHours(0,0,0,0)
return today.getTime()
And as well how can i get the ms of just the current hours and minutes . Something like
const hours = new Date().gethours()
const minutes = new Date().getminutes()
const now = (hours + minutes) in millisecond
thanks
how can I get the ms of the day at midnight with vanilla js ; something like this:
const today = new Date().setHours(0,0,0,0)
return today.getTime()
You're close, but don't use the return value of setHours, use the date object:
const today = new Date();
today.setHours(0,0,0,0);
return today.getTime();
That's working in local time. If you want UTC, use setUTCHours instead.
And as well how can i get the ms of just the current hours and minutes . Something like
const hours = new Date().gethours()
const minutes = new Date().getminutes()
const now = (hours + minutes) in millisecond
The methods are getHours and getMinutes (capitalization matters). If you're trying to get "milliseconds since midnight", it would be:
const dt = new Date();
const msSinceMidnight = ((dt.getHours() * 60) + dt.getMinutes()) * 60 * 1000;
return msSinceMidnight;
...since there are 60 minutes in an hour, 60 seconds in a minute, and 1000ms in a second. (Note that you haven't used getSeconds there, so seconds will be ignored.)
setHours returns the time value of the updated Date, so for the local midnight time value:
let today = new Date().setHours(0,0,0,0);
does the job. If you want local milliseconds since midnight, then:
let msSinceMidnight = new Date() - new Date().setHours(0,0,0,0);
Getting UTC milliseconds since midnight is simpler, as in ECMAScript UTC days are always 8.64e7 ms long:
let msSinceUTCMidnight = new Date() % 8.64e7;
let today = new Date().setHours(0,0,0,0);
console.log(`today: ${today}`);
let msSinceMidnight = new Date() - new Date().setHours(0,0,0,0);
console.log(`msSinceMidnight: ${msSinceMidnight}`);
let msSinceUTCMidnight = new Date() % 8.64e7;
console.log(`msSinceUTCMidnight: ${msSinceUTCMidnight}`);
Related
I want to get Unix timestamp (time in seconds) from tomorrow.
I have tried the following with no success:
var d = new Date();
d.setDate(d.getDay() - 1);
d.setHours(0, 0, 0);
d.setMilliseconds(0);
console.log(d/1000|0)
How would I fix the above?
Just modified your code and it works fine
var d = new Date();
d.setDate(d.getDate() + 1);
d.setHours(0, 0, 0);
d.setMilliseconds(0);
console.log(d)
>> Sun Apr 21 2019 00:00:00 GMT+0530 (India Standard Time)
Hope this will work for you
This should do it.
Copied directly from https://javascript.info/task/get-seconds-to-tomorrow
function getSecondsToTomorrow() {
let now = new Date();
// tomorrow date
let tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate()+1);
let diff = tomorrow - now; // difference in ms
return Math.round(diff / 1000); // convert to seconds
}
console.log(getSecondsToTomorrow());
you could use a third party library like moment js which makes your life alot easier
momentjs
You can use a unix timestamp and add 24*60*60*1000 (same as 86400000) to the current time's timestamp. You can then pass that to new Date() like this:
24 = hours
60 = minutes
60 = seconds
1000 = converts the result to milliseconds
// Current timestamp
const now = Date.now()
// Get 24 hours from now
const next = new Date(now + (24*60*60*1000))
// Create tomorrow's date
const t = new Date(next.getFullYear(), next.getMonth(), next.getDate())
// Subtract the two and divide by 1000
console.log(Math.round((t.getTime() - now) / 1000), 'seconds until tomorrow')
I need to find out if my date is between two dates (for checking birthday whether its between +/- 10 days of current date) without taking care of year (because for birthday we don't need year).
I have tried the following but its typical match and will not ignore year. If i ll compare only date and month then overlap on month end makes problems.
(moment(new Date()).isBetween(moment(date).add(10, 'days'), moment(date).subtract(10, 'days')));
Here is the solution that i was end up with.
const birthDate= new Date(birthDate);
birthDate.setFullYear(new Date().getFullYear());
const isBirthdayAround = Math.abs(birthday - new Date) < 10*24*60*60*1000;
And if you are using moment then:
const birthDate= new Date(birthDate);
birthDate.setFullYear(new Date().getFullYear());
const isBirthdayAround = moment(new Date()).isBetween(moment(birthDate).subtract(10, 'days'), moment(birthDate).add(10, 'days'));
if(Math.abs(birthday - new Date) < 10/*d*/ * 24/*h*/ * 60/*min*/ * 60/*secs*/ * 1000/*ms*/)
alert("somewhat in the range");
You can just work with dates as if they were milliseconds. Just get the difference by subtracting them, then check if its smaller than 10 days in milliseconds.
You can use momentjs with methods subtract and add to find any date you want.
Example:
moment().add(7, 'days'); // next 7 days
moment().subtract(7, 'days'); // 7 days ago
This may be help you.
var birthDate = new Date("05/16/1993");
var day = birthDate.getDate();
var month = birthDate.getMonth();
var currentDate = new Date();
var tempDate = new Date();
var oneDay = 1000 * 60 * 60 * 24
var dayDifference = 10 // you can set here difference
tempDate = new Date(tempDate.setMonth(month,day))
var timeDiff = tempDate.getTime() - currentDate.getTime();
timeDiff = Math.round(timeDiff / oneDay)
if(-dayDifference <= timeDiff && timeDiff <=dayDifference){
alert("matched")
}
else{
alert("not matched")
}
I need to get the local time. I created this script but, for example, in italy ( where I live ), the alert shows 7 instead of 9. Why ?
var time = new Date().getTime();
var seconds = time / 1000;
seconds = seconds % 86400;
hours = parseInt(seconds / 3600);
alert(hours);
Because getTime returns the timestamp in milliseconds. And the timestamp is timezone independent. Use getTimezoneOffset() to get the offset in minutes from UTC, and add it.
new Date().getHours() will give you the local time, no adjustment needed.
new Date().getTimezoneOffset() will give you the number of minutes from UTC in the users's locale, should you need to offset an absolute time.
Note that UNIX timestamps measure the number of seconds since the UNIX epoch as if every day was exactly 3600 * 24 seconds. That allows you to get the time on most days with divisions and modulos, but if your timestamp is earlier than the latest leap second, and you try to do some simple maths with it, the result will not be accurate.
DEMO : http://jsfiddle.net/yk3wkcr8/
var currentTime = new Date();
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
alert(h);
alert(m);
alert(s);
If you want an example, try this: Fiddle
It uses full array with seconds, minutes, hours, date, day and year.
BTW you can use getHours(); followed by the others.
var d = new Date(),
hours = d.getHours(),
hour = (hours - 12),
year = d.getFullYear(),
second = d.getSeconds(),
minute = d.getMinutes();
alert (hour + ":" + minute + ":" + second);
etc, etc.
You can try this:
new Date().toLocaleString()
it will give you something like:
"4/16/2015, 9:14:53 AM"
And if you need to obtain only the time stamp then you can split the resulting string into an array and get the second item from the array:
new Date().toLocaleString().split(',')[1]
If you need only the hours this is the way:
new Date().getHours()
$(document).ready(function() {
var date = new Date();
var data_new = [];var url ='http://www.domain.com /kjdshlka/api.php?date=2014-07-15';
$.getJSON(url,function(result) {
var elt = [date,result.requests];data_new.push(elt);console.log(data_new);
});
});
I am struggling to decrement the date by one day using javascript for loop.Here is my code,from the url im getting some requests.like if i decrease the date by one day other requests will come .Now i need this process for 7days using javascript for loop.Can anybody please tel me how to do ?
var date = new Date(); // Date you want, here I got the current date and time
date.setDate(date.getDate()-1);
getDate() will give you the date, then reduce it by 1 and using setDate() you can replace date again.
var today = new Date();
var yesterday = new Date(today.getTime() - (24 * 60 * 60 * 1000)); //(hours * minutes * seconds * milliseconds)
console.log(yesterday);
var now = new Date();
console.log(now);
var yesterday = new Date(now - 86400000);
console.log(yesterday);
/* In a Decrement Loop*/
for(var i=100;i>0;i--){
console.log(new Date(now - i*86400000));
}
It seems that JavaScript's Date() function can only return local date and time. Is there anyway to get time for a specific time zone, e.g., GMT-9?
Combining #Esailija and #D3mon-1stVFW, I figured it out: you need to have two time zone offset, one for local time and one for destination time, here is the working code:
var today = new Date();
var localoffset = -(today.getTimezoneOffset()/60);
var destoffset = -4;
var offset = destoffset-localoffset;
var d = new Date( new Date().getTime() + offset * 3600 * 1000)
An example is here: http://jsfiddle.net/BBzyN/3/
var offset = -8;
new Date( new Date().getTime() + offset * 3600 * 1000).toUTCString().replace( / GMT$/, "" )
"Wed, 20 Jun 2012 08:55:20"
<script>
var offset = -8;
document.write(
new Date(
new Date().getTime() + offset * 3600 * 1000
).toUTCString().replace( / GMT$/, "" )
);
</script>
You can do this in one line:
let d = new Date(new Date().toLocaleString("en-US", {timeZone: "timezone id"})); // timezone ex: Asia/Jerusalem
var today = new Date();
var offset = -(today.getTimezoneOffset()/60);
You can always get GMT time (so long as the client's clock is correct).
To display a date in an arbitrary time-zone, construct a string from the UTC hours, minutes, and seconds after adding the offset.
There is simple library for working on timezones easily called TimezoneJS can be found at https://github.com/mde/timezone-js.