Get the correct local time - javascript

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

Related

getHours function not working in date difference

[code][1]
Hi I am trying to find the difference between these 2 dates and would like the answer to be set like this - 00:00:00. I have "current" set to a as 00:00:00 but would like the time stamp to be updated to however many hours, min, seconds there are between the 2 days. I'm being told that the getHours, getMinutes, and getSeconds function is not a thing. How do I go about fixing this? [1]: https://i.stack.imgur.com/1GY5B.png
I guess you didnt convert the time to a Date.
look at my example:
function updateTime(){
var event = new Date("April 1, 2021 8:30:00").getTime();
var now = new Date().getTime();
var a = (event - now);
var d = new Date(a);
var hours = d.getHours(),
minutes = d.getMinutes(),
seconds = d.getSeconds(),
ampm = "AM";
if (hours>12) ampm = "PM";
console.log(`${hours}:${minutes}:${seconds} ${ampm}`)
}
updateTime();
Is this what you try to do?
PS:
However I would also multiply the hours with the days or I would also add days if days > 0
And the "AM" is kinda unnecessary for getting a difference

set hours and get ms with Date in js

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

Javascript function to calculate the hours remaining to specific date or time

I need to count the remaining time in hours between today or actual date/time and a specific end date at 00:00 hrs.
I tried in this fiddle, but I get the counting of one month more than it should be.
https://jsfiddle.net/alonsoct/52ts89mz/
var endTime = new Date(2019,10,18,0,0,0) / 1000;
function setClock() {
var elapsed = new Date() / 1000;
var totalTime = endTime - elapsed;
var hr = parseInt(totalTime / 3600)
var min = parseInt(totalTime / 60) % 60;
var sec = parseInt(totalTime % 60, 10);
var result = hr + " hours, " + min + " minutes " + sec + " seconds";
document.getElementById('timeRemaining').innerHTML = result;
setTimeout(setClock, 1000);
}
setClock();
If I enter one month less in the "endTime" variable I get the correct result in hours count, but this is not fine I need to enter the real end date without the need to subtract one month.
Thanks
The code below is mostly your code with one change. I changed the input for endTime to an ISO format and omitted the time Zone. This, in theory, will default to your browser's timezone. I tested on your linked and it worked. Here is some additional information https://www.w3schools.com/js/js_date_formats.asp
var endTime = new Date("2019-10-18T00:00:00") / 1000;
function setClock() {
var elapsed = new Date() / 1000;
var totalSec = endTime - elapsed;
var h = parseInt( totalSec / 3600 )
var m = parseInt( totalSec / 60 ) % 60;
var s = parseInt(totalSec % 60, 10);
var result = h + " hours, " + m + " minutes " + s + " seconds";
document.getElementById('timeRemaining').innerHTML = result;
setTimeout(setClock, 1000);
}
setClock();
Here is a working solution with Vanilla JS:
var calcTime = setInterval(function(){
date_future = new Date(2019,10,18,0,0,0)
date_now = new Date();
seconds = Math.floor((date_future - (date_now))/1000);
minutes = Math.floor(seconds/60);
hours = Math.floor(minutes/60);
days = Math.floor(hours/24);
hours = hours-(days*24);
minutes = minutes-(days*24*60)-(hours*60);
seconds = seconds-(days*24*60*60)-(hours*60*60)-(minutes*60);
It's pretty easier with JQuery → http://hilios.github.io/jQuery.countdown/examples/show-total-hours.html
JavaScript counts months from 0 to 11.
January is 0. December is 11.
I think you were thinking that endTime will be October 18th, 2019 but actually it's November 18th, 2019.
You can see more relevant information here.
https://www.w3schools.com/js/js_dates.asp
Thanks.
If between the start-datetime and end-datetime a change takes place in winter / summertime remember to make summertime/wintertime adjustments
(if you get these values from e.g. an api:) if the startdate is specified by a client in location x and enddate is specified in location y, you have take into account that the startdate could potentially be in 00:00:00+14:00 timezone and end the endate in max -14 timezone.
if you only present 2 timeboxes: time 1 and time 2, you can map these anywhere on a 52 hours time-scale: -14 , +14 and the 24 hours gmt timescale where you then would normalize to. ( 0:00 could mean i am in Samoa +14, 14 hours ahead of the end of GMT 23:59:59 (14 further) or ahead of GMT 0:00 (14+24 further). Then there are countries which make local time decisions e.g. in India with +5.5 UTC or Burma +6.5 or newfoundland -3.5.
Since this is stackexchange and people will copy and paste these examples in their applications even if these applications are "on the internet" and so DO have users from every location in the world.
Therefore ... use a library: https://momentjs.com/ ; Get hours difference between two dates in Moment Js they have a helper https://momentjs.com/docs/#/displaying/to/ and see also: Moment.js - How To Detect Daylight Savings Time And Add One Day
You can see the same bug on https://www.timeanddate.com/countdown but they added in words : https://www.timeanddate.com/countdown/one-hour-offwintertijd (and they assume the end datetime is in the same location as the countdown datetime)

Javascript and mySQL dateTime stamp difference

I have a mySQL database in which I store the time in this format automatically:
2015-08-17 21:31:06
I am able to retrieve this time stamp from my database and bring it into javascript. I want to then get the current date time in javascript and determine how many days are between the current date time and the date time I pulled from the database.
I found this function when researching how to get the current date time in javascript:
Date();
But it seems to return the date in this format:
Tue Aug 18 2015 10:49:06 GMT-0700 (Pacific Daylight Time)
There has to be an easier way of doing this other than going character by character and picking it out from both?
You can build a new date in javascript by passing the data you receive from your backend as the first argument.
You have to make sure that the format is an accepted one. In your case we need to replace the space with a T. You may also be able to change the format from the back end.
Some good examples are available in the MDN docs.
var d = new Date("2015-08-17T21:31:06");
console.log(d.getMonth());
To calculate the difference in days you could do something like this:
var now = new Date();
var then = new Date("2015-08-15T21:31:06");
console.log((now - then)/1000/60/60/24);
You can select the difference directly in your query:
SELECT DATEDIFF(now(), myDateCol) FROM myTable;
the Date object has a function called getTime(), which will give you the current timestamp in milliseconds. You can then get the diff and convert to days by dividing by (1000 * 3600 * 24)
e.g.
var date1 = new Date()
var date2 = new Date()
var diffInMs = date2.getTime() - date1.getTime()
var diffInDays = diffInMs/(1000*3600*24)
Since none of the other answer got it quite right:
var pieces = "2015-08-17 21:31:06".split(' ');
var date = pieces[0].split('-');
var time = pieces[1].split(':');
var yr = date[0], mon = date[1], day = date[2];
var hour = time[0], min = time[1], sec = time[2];
var dateObj = new Date(yr, mon, day, hr, min, sec);
//if you want the fractional part, omit the call to Math.floor()
var diff = Math.floor((Date.now() - dateObj.getTime()) / (1000 * 60 * 60 * 24));
Note that none of this deals with the timezone difference between the browser and whatever you have stored in the DB. Here's an offset example:
var tzOff = new Date().getTimezoneOffset() * 60 * 1000; //in ms

Increment JavasScript date object for next month when days are increased?

Is there a simple solution to auto increment the month of the date object when days are added via getDate?
I need to add 2 days to a user supplied date, for example if the user's entered value is 2014-11-16 it returns 2014-11-18.
I have this working in the below example, but the problem is if a user supplies a date at the end of the month, for example 2014-11-30 it will return 2014-11-32 (November only has 30 days) instead of rolling into the next month, it should be 2014-12-02.
It also does not increment to a new year as well.
var actualDate = new Date(arrive);
var year = actualDate.getFullYear();
var monthy = actualDate.getMonth()+1;
var days = actualDate.getDate()+2;
var out = year + '-' + (monthy < 10 ? '0' : '') + monthy + '-' + days;
http://jsfiddle.net/bubykx1t/
Just use the setDate() method.
var actualDate = new Date(arrive);
actualDate.setDate(actualDate.getDate() + 2);
Check out this link
You can create new Date objects based on the number of milliseconds since January 1, 1970, 00:00:00 UTC. Since the number of milliseconds in a minute, hour, day, week are set we can add a fixed amount to the current time in order to get a time in the future. We can forget about what day of the month, or year it is as it's inherent in the number of milliseconds that have passed since 1970.
This will keep adjust to days months and years correctly.
var numberOfDaysToIncrement = 7;
var offset = numberOfDaysToIncrement * 24 * 60 * 60 * 1000;
var date = new Date();
var dateIncremented = new Date(date.getTime() + offset);

Categories

Resources