How can I get todays timestamp at 4pm? - javascript

I am looking for a way to receive the timestamp of today's 4pm in JavaScript.
When I use this code
Math.floor(Date.now() / 1000);
it give me the current timestamp. How can I specify just the hour to be static, the rest to rely on the current day?

You can do this by getting the current DateTime and change the hour, code:
var d = new Date();
d.setHours(16,0,0,0);//The setHours method can take optional minutes, seconds and ms arguments, but you can also do setHours(16)
Math.floor(d / 1000);

Here is the code to do that:
var d = new Date();//stores current date time
d.setHours(16);//4pm = 16 in 24 hour time
Now when you'll type console.log(d), you'll get the following required result.
Tue May 12 2015 20:58:24 GMT+0500 (PKT)

Try:
var date = new Date();
date.setHours(16);
date.setMinutes(0);
date.setSeconds(0);
Math.floor(date.getTime() / 1000);

Instantiate a Date object and set the hours like so:
var d = new Date;
d.setHours(16);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours

Related

set midnight in javascript for cookie expiration

Good morning, I currently have this script:
now = new Date (). getTime ();
now = now + 86400000;
this takes the current date and time and adds 24 hours to it.
Instead, I would need to set midnight of the current day. I tried with:
var d = new Date ();
date = d.setHours (0,0,0,0);
now = date / 1000;
but it does not work! I need this to set the expiration of a cookie:
$ .cookies.set ('mycookie2250', 'true', {expiresAt: new Date (now)});
in the first case it works but in the second it doesn't.
Where am I wrong?
var date = new Date();
date.setHours(0,0,0,0);
// date is midnight.

invalid date format TypeScript

I am passing in time values departureTime such as '12:00' here. Then I try to convert it into a date and perform a subtraction. However, the result of timeOfDeparture and then time till departure is invalid. How can I fix this and make everything in a uniform type?
const timeNow = new Date();
console.log('TIME NOW', timeNow)
const timeOfDeparture = new Date(departureTime);
console.log('TIME of Departure', timeOfDeparture)
const timeTillDeparture = Math.floor((timeOfDeparture.valueOf() - timeNow.valueOf()) / 60000);
console.log('TIME TILL DEP', timeOfDeparture)
Example console logs:
TIME NOW Tue Oct 06 2020 15:47:35 GMT+0200 (Central European Summer Time)
TIME of Departure Invalid Date
TripTimes.tsx:17 TIME TILL DEP NaN
The date object doesn't take hours as an argument. you can read more about it here
There are four ways of instantiating a date:
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
If your app relies on date manipulation, or if you want to manipulate dates more easily, consider using helper libraries like momentJs.
For example, if your departure time is on the same date but just on a different hour, your departure time using momentJs will be
moment().hour(departureHour).minute(departureMinute);
When you are creating a Javascript Date object you cannot pass only hours and minutes. You can use the empty constructor or data constructor
new Date(year, month, date, hours, minutes, seconds, ms)
but the first two arguments (year and month) are obligatory at least. You could get data from timeNow and add the time values from departureTime. Example:
const timeNow = new Date();
console.log('TIME NOW', timeNow)
let departureTimeArray = departureTime.split(":");
console.log('Hour of Departure', departureTimeArray[0]);
console.log('Minutes of Departure', departureTimeArray[1]);
const timeOfDeparture = new Date(timeNow.getFullYear(), timeNow.getMonth(), timeNow.getDate(), departureTimeArray[0], departureTimeArray[1]);
console.log('TIME of Departure', timeOfDeparture);
const timeTillDeparture = Math.floor((timeOfDeparture.valueOf() - timeNow.valueOf()) / 60000);
console.log('TIME TILL DEP', timeOfDeparture)
I hope this solution helps you.

JavaScript setHours() and getHours() [duplicate]

I am trying to subtract hours from a given date time string using javascript.
My code is like:
var cbTime = new Date();
cbTime = selectedTime.setHours(-5.5);
Where selectedTime is the given time (time that i pass as parameter).
So suppose selectedTime is Tue Sep 16 19:15:16 UTC+0530 2014
Ans I get is : 1410875116995
I want answer in datetime format.
Am I doing something wrong here? Or there is some other solution?
The reason is that setHours(), setMinutes(), etc, take an Integer as a parameter. From the docs:
...
The setMinutes() method sets the minutes for a specified date
according to local time.
...
Parameters:
An integer between 0 and 59, representing the minutes.
So, you could do this:
var selectedTime = new Date(),
cbTime = new Date();
cbTime.setHours(selectedTime.getHours() - 5);
cbTime.setMinutes(selectedTime.getMinutes() - 30);
document.write('cbTime: ' + cbTime);
document.write('<br>');
document.write('selectedTime: ' + selectedTime);
Well first off setting the hours to -5.5 is nonsensical, the code will truncate to an integer (-5) and then take that as "five hours before midnight", which is 7PM yesterday.
Second, setHours (and other functions like it) modify the Date object (try console.log(cbTime)) and return the timestamp (number of milliseconds since the epoch).
You should not rely on the output format of the browser converting the Date object to a string for you, and should instead use get*() functions to format it yourself.
According to this:
http://www.w3schools.com/jsref/jsref_sethours.asp
You'll get "Milliseconds between the date object and midnight January 1 1970" as a return value of setHours.
Perhaps you're looking for this:
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_sethours3
Edit:
If you want to subtract 5.5 hours, first you have to subtract 5 hours, then 30 minutes. Optionally you can convert 5.5 hours to 330 minutes and subtract them like this:
var d = new Date();
d.setMinutes(d.getMinutes() - 330);
document.getElementById("demo").innerHTML = d;
Use:
var cbTime = new Date();
cbTime.setHours(cbTime.getHours() - 5.5)
cbTime.toLocaleString();
try this:
var cbTime = new Date();
cbTime.setHours(cbTime.getHours() - 5.5)
cbTime.toLocaleString();

Json date format conversion subtracting 1 day

The date format i receive from JSON is like this :-
/Date(1412101800000)/
When i convert this into dateformat, i get 1 day minus.
I am using following code :-
var dateFormat = new Date(parseInt(obj['DATEOFJOINING'].substr(6))).toISOString().substr(0, 10);
dateFormat results in 2014-09-30
The Original Date which comes from Db is 2014-10-01
Why is this happening? How to get perfect date?
It's a timestamp.
new Date(parseInt('/Date(1412101800000)/'.substr(6)));
Just set a right timezone.
var dateFormat = new Date(parseInt('/Date(1412101800000)/'.substr(6)));
dateFormat.setTime( dateFormat.getTime() + dateFormat.getTimezoneOffset()*60*1000 );
Date in your timezone*: 30/09/2014 19:30:00
Date in Los Angeles*: 30/09/2014 11:30:00
Date in Berlin* :30/09/2014 19:30:00
Date in Beijing*: 01/10/2014 01:30:00
Date in New York* :30/09/2014 13:30:00
For example
var dateFormat = new Date(parseInt('/Date(1412101800000)/'.substr(6)));
dateFormat.setTime( dateFormat.getTime() + dateFormat.getTimezoneOffset()*(-10*100000));
Date {Wed Oct 01 2014 12:10:00 GMT+0100 (BST)}
As #madforstrength commented, it uses the offset from GMT.
To get the offset in minutes you can try:
var d = new Date()
var n = d.getTimezoneOffset();
and adjust for your local time.
You can see a reference here.
This is due to the clients timezone. Use Date.prototype.getTimezoneOffset to get the offset:
var date = new Date(1412101800000);
var gmtDate = new Date(date.valueOf() + date.getTimezoneOffset() * 60 * 1000);

Convert UTC Epoch to local date

I have been fighting with this for a bit now. I’m trying to convert epoch to a date object. The epoch is sent to me in UTC. Whenever you pass new Date() an epoch, it assumes it’s local epoch. I tried creating a UTC object, then using setTime() to adjust it to the proper epoch, but the only method that seems useful is toUTCString() and strings don’t help me. If I pass that string into a new date, it should notice that it’s UTC, but it doesn’t.
new Date( new Date().toUTCString() ).toLocaleString()
My next attempt was to try to get the difference between local current epoch and UTC current epoch, but I wasn’t able to get that either.
new Date( new Date().toUTCString() ).getTime() - new Date().getTime()
It’s only giving me very small differences, under 1000, which is in milliseconds.
Any suggestions?
I think I have a simpler solution -- set the initial date to the epoch and add UTC units. Say you have a UTC epoch var stored in seconds. How about 1234567890. To convert that to a proper date in the local time zone:
var utcSeconds = 1234567890;
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(utcSeconds);
d is now a date (in my time zone) set to Fri Feb 13 2009 18:31:30 GMT-0500 (EST)
It's easy, new Date() just takes milliseconds, e.g.
new Date(1394104654000)
> Thu Mar 06 2014 06:17:34 GMT-0500 (EST)
And just for the logs, I did this using Moment.js library, which I was using for formatting anyway.
moment.utc(1234567890000).local()
>Fri Feb 13 2009 19:01:30 GMT-0430 (VET)
Epoch time is in seconds from Jan. 1, 1970. date.getTime() returns milliseconds from Jan. 1, 1970, so.. if you have an epoch timestamp, convert it to a javascript timestamp by multiplying by 1000.
function epochToJsDate(ts){
// ts = epoch timestamp
// returns date obj
return new Date(ts*1000);
}
function jsDateToEpoch(d){
// d = javascript date obj
// returns epoch timestamp
return (d.getTime()-d.getMilliseconds())/1000;
}
function ToLocalDate (inDate) {
var date = new Date();
date.setTime(inDate.valueOf() - 60000 * inDate.getTimezoneOffset());
return date;
}
Epoch time (i.e. Unix Epoch time) is nearly always the number of seconds that have expired since 1st Jan 1970 00:00:00 (UTC time), not the number of milliseconds which some of the answers here have implied.
https://en.wikipedia.org/wiki/Unix_time
Therefore, if you have been given a Unix Epoch time value it will probably be in seconds, and will look something like 1547035195. If you want to make this human readable in JavaScript, you need to convert the value to milliseconds, and pass that value into the Date(value) constructor, e.g.:
const unixEpochTimeMS = 1547035195 * 1000;
const d = new Date(unixEpochTimeMS);
// Careful, the string output here can vary by implementation...
const strDate = d.toLocaleString();
You don't need to do the d.setUTCMilliseconds(0) step in the accepted answer because the JavaScript Date(value) constructor takes a UTC value in milliseconds (not a local time).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Syntax
Also note that you should avoid using the Date(...) constructor that takes a string datetime representation, this is not recommended (see the link above).
var myDate = new Date( your epoch date *1000);
source - https://www.epochconverter.com/programming/#javascript
To convert the current epoch time in [ms] to a 24-hour time. You might need to specify the option to disable 12-hour format.
$ node.exe -e "var date = new Date(Date.now()); console.log(date.toLocaleString('en-GB', { hour12:false } ));"
2/7/2018, 19:35:24
or as JS:
var date = new Date(Date.now());
console.log(date.toLocaleString('en-GB', { hour12:false } ));
// 2/7/2018, 19:35:24
console.log(date.toLocaleString('en-GB', { hour:'numeric', minute:'numeric', second:'numeric', hour12:false } ));
// 19:35:24
Note: The use of en-GB here, is just a (random) choice of a place using the 24 hour format, it is not your timezone!
Addition to the above answer by #djechlin
d = '1394104654000';
new Date(parseInt(d));
converts EPOCH time to human readable date. Just don't forget that type of EPOCH time must be an Integer.
The Easiest Way
If you have the unix epoch in milliseconds, in my case - 1601209912824
convert it into a Date Object as so
const dateObject = new Date(milliseconds)
const humanDateFormat = dateObject.toString()
output -
Sun Sep 27 2020 18:01:52 GMT+0530 (India Standard Time)
if you want the date in UTC -
const dateObject = new Date(milliseconds)
const humanDateFormat = dateObject.toUTCString()
Now you can format it as you please.
Considering, you have epoch_time available,
// for eg. epoch_time = 1487086694.213
var date = new Date(epoch_time * 1000); // multiply by 1000 for milliseconds
var date_string = date.toLocaleString('en-GB'); // 24 hour format
The simplest solution I've found to this, is:
var timestamp = Date.now(), // returns milliseconds since epoch time
normalisedTime = new Date(timestamp);
Notice this doesn't have the * 1000 at the end of new Date(timestamp) statement as this (for me anyway!) always seems to give out the wrong date, ie instead of giving the year 2019 it gives the year as 51015, so just bear that in mind.
EDIT
var utcDate = new Date(incomingUTCepoch);
var date = new Date();
date.setUTCDate(utcDate.getDate());
date.setUTCHours(utcDate.getHours());
date.setUTCMonth(utcDate.getMonth());
date.setUTCMinutes(utcDate.getMinutes());
date.setUTCSeconds(utcDate.getSeconds());
date.setUTCMilliseconds(utcDate.getMilliseconds());
EDIT fixed
Are you just asking to convert a UTC string to a "local" string? You could do:
var utc_string = '2011-09-05 20:05:15';
var local_string = (function(dtstr) {
var t0 = new Date(dtstr);
var t1 = Date.parse(t0.toUTCString().replace('GMT', ''));
var t2 = (2 * t0) - t1;
return new Date(t2).toString();
})(utc_string);
If you prefer to resolve timestamps and dates conversions from and to UTC and local time without libraries like moment.js, take a look at the option below.
For applications that use UTC timestamps, you may need to show the date in the browser considering the local timezone and daylight savings when applicable. Editing a date that is in a different daylight savings time even though in the same timezone can be tricky.
The Number and Date extensions below allow you to show and get dates in the timezone of the timestamps. For example, lets say you are in Vancouver, if you are editing a date in July or in December, it can mean you are editing a date in PST or PDT.
I recommend you to check the Code Snippet down below to test this solution.
Conversions from milliseconds
Number.prototype.toLocalDate = function () {
var value = new Date(this);
value.setHours(value.getHours() + (value.getTimezoneOffset() / 60));
return value;
};
Number.prototype.toUTCDate = function () {
var value = new Date(this);
value.setHours(value.getHours() - (value.getTimezoneOffset() / 60));
return value;
};
Conversions from dates
Date.prototype.getUTCTime = function () {
return this.getTime() - (this.getTimezoneOffset() * 60000);
};
Usage
// Adds the timezone and daylight savings if applicable
(1499670000000).toLocalDate();
// Eliminates the timezone and daylight savings if applicable
new Date(2017, 6, 10).getUTCTime();
See it for yourself
// Extending Number
Number.prototype.toLocalDate = function () {
var value = new Date(this);
value.setHours(value.getHours() + (value.getTimezoneOffset() / 60));
return value;
};
Number.prototype.toUTCDate = function () {
var value = new Date(this);
value.setHours(value.getHours() - (value.getTimezoneOffset() / 60));
return value;
};
// Extending Date
Date.prototype.getUTCTime = function () {
return this.getTime() - (this.getTimezoneOffset() * 60000);
};
// Getting the demo to work
document.getElementById('m-to-local-button').addEventListener('click', function () {
var displayElement = document.getElementById('m-to-local-display'),
value = document.getElementById('m-to-local').value,
milliseconds = parseInt(value);
if (typeof milliseconds === 'number')
displayElement.innerText = (milliseconds).toLocalDate().toISOString();
else
displayElement.innerText = 'Set a value';
}, false);
document.getElementById('m-to-utc-button').addEventListener('click', function () {
var displayElement = document.getElementById('m-to-utc-display'),
value = document.getElementById('m-to-utc').value,
milliseconds = parseInt(value);
if (typeof milliseconds === 'number')
displayElement.innerText = (milliseconds).toUTCDate().toISOString();
else
displayElement.innerText = 'Set a value';
}, false);
document.getElementById('date-to-utc-button').addEventListener('click', function () {
var displayElement = document.getElementById('date-to-utc-display'),
yearValue = document.getElementById('date-to-utc-year').value || '1970',
monthValue = document.getElementById('date-to-utc-month').value || '0',
dayValue = document.getElementById('date-to-utc-day').value || '1',
hourValue = document.getElementById('date-to-utc-hour').value || '0',
minuteValue = document.getElementById('date-to-utc-minute').value || '0',
secondValue = document.getElementById('date-to-utc-second').value || '0',
year = parseInt(yearValue),
month = parseInt(monthValue),
day = parseInt(dayValue),
hour = parseInt(hourValue),
minute = parseInt(minuteValue),
second = parseInt(secondValue);
displayElement.innerText = new Date(year, month, day, hour, minute, second).getUTCTime();
}, false);
<link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.11/semantic.css" rel="stylesheet"/>
<div class="ui container">
<p></p>
<h3>Milliseconds to local date</h3>
<input id="m-to-local" placeholder="Timestamp" value="0" /> <button id="m-to-local-button">Convert</button>
<em id="m-to-local-display">Set a value</em>
<h3>Milliseconds to UTC date</h3>
<input id="m-to-utc" placeholder="Timestamp" value="0" /> <button id="m-to-utc-button">Convert</button>
<em id="m-to-utc-display">Set a value</em>
<h3>Date to milliseconds in UTC</h3>
<input id="date-to-utc-year" placeholder="Year" style="width: 4em;" />
<input id="date-to-utc-month" placeholder="Month" style="width: 4em;" />
<input id="date-to-utc-day" placeholder="Day" style="width: 4em;" />
<input id="date-to-utc-hour" placeholder="Hour" style="width: 4em;" />
<input id="date-to-utc-minute" placeholder="Minute" style="width: 4em;" />
<input id="date-to-utc-second" placeholder="Second" style="width: 4em;" />
<button id="date-to-utc-button">Convert</button>
<em id="date-to-utc-display">Set the values</em>
</div>
#Amjad, good idea, but a better implementation would be:
Date.prototype.setUTCTime = function(UTCTimestamp) {
var UTCDate = new Date(UTCTimestamp);
this.setUTCFullYear(UTCDate.getFullYear(), UTCDate.getMonth(), UTCDate.getDate());
this.setUTCHours(UTCDate.getHours(), UTCDate.getMinutes(), UTCDate.getSeconds(), UTCDate.getMilliseconds());
return this.getTime();
}

Categories