setHours is not a function when converting time from string - javascript

I am trying to compare a time in string format to the current time. I've tried setting up two Date objects and calling .Now() on both of them, then on one of them adjusting the time to the time that is in string format by splitting it and parsing both the hours and minutes to integers, but I get the following error:
setHours is not a function
The 'cutoff' value I'm using is '15:00' and when following in the debugger I can see this splits in to split[0] = 15 and split[1] = 00 (this is before they are parsed into integers.
var cutoff = data.CutOff;
var split = cutoff.split(":");
var today = Date.now();
var hours = parseInt(split[0]);
var min = parseInt(split[1]);
today.setHours(hours, min);
if (Date.now() < today) {
// Do Something
}

You want to do new Date() as opposed to Date.now()
new Date creates a Date instance which allows you to access the Date methods.
Date.now() method returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.

Related

How do i get remaining seconds of future date in javascript

So i have an API, which gives me date format like this 11/21/2022 19:00:00 what i need to do is i have to schedule notification for this datetime, but the problem is i am using react-native/expo which accepts the scheduling time in seconds.
How do i convert this datetime to seconds, i mean if today's date is 11/15/2022 12:00:00 and the date on which the notification should be scheduled is 11/16/2022 12:00:00 which means the future date in 1 day ahead of todays date, and 1 day is equal to 86400 seconds, which means i have to trigger notification after 86400 seconds. So how do i get the remaining seconds of the upcoming date?
Use .getTime()
function Date.prototype.getTime() returns number of milliseconds since start of epoch (1/1/1970)
get the number of milliseconds and divide it 1000 to seconds
subtract (round) and you have the difference
according to Date.parse() is only ISO 8601 format of ECMA262 string supported, so use:
new Date("2022-11-16T12:00:00Z")
or new Date(2022,10,16,12)
rather not n̶e̶w̶ ̶D̶a̶t̶e̶(̶"̶1̶1̶/̶2̶1̶/̶2̶0̶2̶2̶ ̶1̶9̶:̶0̶0̶:̶0̶0̶"̶)̶ that can lead to unexpected behaviour
const secondsInTheFuture = new Date("2022-11-16T12:00:00Z").getTime() / 1000;
const secondsNow = new Date().getTime() / 1000;
const difference = Math.round(secondsInTheFuture - secondsNow);
console.log({ secondsInTheFuture, secondsNow, difference });
You can get the epoch time in js with the function + new Date, if you are passing any date value, to new Date(dateValue), please make sure to stringify.
+ new Date
To get the diff b/w these two dates in seconds,
const initialDate = '11/15/2022 12:00:00'
const futureDate = '11/16/2022 12:00:00'
const diffInSeconds = (+ new Date(futureDate) - + new Date(initialDate)) / 1000
ps: epoch time is in milliseconds, hence dividing by 1000.
Solved using dayjs package
const dayjs = require("dayjs")
const d1 = dayjs("2022-11-15 13:00")
const d2 = dayjs("2022-11-16 12:00")
const res = d1.diff(d2) / 1000 // ÷ by 1000 to get output in seconds
console.log(res)

Convert JavaScript date to Swift JSON timeIntervalSinceReferenceDate format

Given a JavaScript date, how can I convert this to the same format as Swift JSON encoding?
e.g. I would like to get a value of 620102769.132999 for the date 2020-08-26 02:46:09
The default Swift JSON encoding outputs a value which is the number of seconds that have passed since ReferenceDate. https://developer.apple.com/documentation/foundation/jsonencoder/2895363-dateencodingstrategy
It seems ReferenceDate is 00:00:00 UTC on 1 January 2001.
https://developer.apple.com/documentation/foundation/nsdate/1409769-init
function dateToSwiftInterval(date: Date): number {
const referenceDate = Date.UTC(2001,0,1);
const timeSpanMs = (date - referenceDate);
return timeSpanMs / 1000;
}
const myDate = new Date(1598366769000);
console.log(dateToSwiftValue(myDate)); // 620102769
As Elwyn says, Swift represents dates as time intervals that are seconds since 1 Jan 2001 UTC. Javascript Dates use milliseconds since 1 Jan 1970 UTC, so all you need to do is adjust by the reference date difference and divide by 1000, e.g.
// Javascript function to convert a Date to a Swift time interval
// date is a Javascript Date, defaults to current date and time
function toSwiftTI(date = new Date()) {
return (date - Date.UTC(2001,0,1)) / 1000;
}
console.log(toSwiftTI());
Since the time difference is a constant, 978307200000, you might just use that instead of calculating it every time, so:
return (date - 978307200000) / 1000;
Going the other way, just multiply by 1,000 and add the constant:
function swiftToDate(ti) {
return new Date(ti * 1000 + 978307200000);
}
console.log(swiftToDate(620102769.132999).toISOString());

Compare time with date in express

I want to compare two dates with time and i want if time difference more than one minute then expire message should display otherwise verify message should display.How can i do this here is my code
var dateFormat = require('dateformat');
var day=dateFormat(new Date(date), "yyyy-mm-dd h:MM:ss"); //2018-08-01 11:02:27
var currenttime=dateFormat(new Date(), "yyyy-mm-dd h:MM:ss"); //2018-08-01 11:08:48
var compare = day - currenttime;
console.log(compare);
Using a JavaScript Date object you can use Date.valueOf() to get the milliseconds from the epoch of that time and then do plain subtraction to get the difference. If it is greater than 60000 then expire.
// I swapped your values on either side of the subtraction operator
// to prevent a negative time difference
var compare = currentTime.valueOf() - day.valueOf()
var isExpired = compare >= 60000
console.log('isExpired', isExpired)
You can compare after generating timestamp of both time. Few ways to generate timestamp
1) +new Date()
2) https://momentjs.com/
Example using moment js :
var compare = moment().format('X') - moment("1995-12-25").format('X'); // In seconds

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

Javascript: how to add n minutes to unix timestamp

I have a unix timestamp: 1368435600. And a duration in minutes: 75 for example.
Using javascript I need to:
Convert the timestamp to a string format hours:mins (09:00)
Add n minutes to the timestamp: timestamp + 75mins
I tried the moment.js library:
end_time = moment(start_time).add('m', booking_service_duration);
booking_service_duration was 75 but it added an hour. I'd also rather not have to use another js library
To add 75 minutes, just multiply by 60 to get the number of seconds, and add that to the timestamp:
timestamp += 75 * 60
To convert to hours:mins you will have to do a bit more math:
var hours = Math.floor(timestamp/60/60),
mins = Math.floor((timestamp - hours * 60 * 60) / 60),
output = hours%24+":"+mins;
Unix time is the number of seconds that have elapsed since 1 January 1970 UTC.
To move that time forward you simply add the number of seconds.
So once you have the minutes, the new timestamp is oldTime + 60*minutes
For the conversion look up parsing libraries, there is code out there for this, do some research.
So you want to convert a timestamp you have, timestamp, to locale time string after adding some time interval, specifically minutes, to it.
Whether you have a kind of date-time string or a kind of epoch mili/seconds, just create a Date object:
const date = new Date(timestamp);
Keep in mind since what you need to do require to add/substract some numbers (your case: minutes) to another number, not some date object or some date-time string, and that number is the epoch mili/secods of your date. So, always you will need the number representation of your date in mili/seconds. JavaScript Date.prototype.getTime() does return epoch miliseconds of your date. Use it:
const miliseconds = date.getTime();
Add as many as miliseconds to it:
const newMiliseconds = miliseconds + (75 * 60 * 1000);
After that, as you said you need a date-time string, well a portion of it; locale time string, you will need to go all the way back; from numbers to date object and to a date-time string:
const newDate = new Date(newMiliseconds);
const newTimestamp = newDate.toString();
Or instead of getting the whole string of it, use the following specialized method to get the format/portion of the string representation of the date object that you like directly:
const newTimestamp = newDate.toLocaleTimeString(); // "12:41:43"
Finally, all you have to do is to just strip the last semicolon and seconds to get hours:minutes format:
const newHoursMins = newTimestamp.slice(0, -3);
Better make a function of it:
function timestampPlus(timestamp, milisecondsDifference, toStringFunc = Date.prototype.toString) {
const date = new Date(timestamp);
const miliseconds = date.getTime();
const newMiliseconds = miliseconds + milisecondsDifference;
const newDate = new Date(newMiliseconds);
const newTimestamp = toStringFunc.call(newDate); // a bit advanced stuff here to let you define once and use whatever kind to string method you want to use, defaults to toString()
return newTimestamp;
}
I left the final formatting out here. You can use this for substraction as well by pasing a negative second argument. Note the seconds argument is in miliseconds and unix timestamp varies and might given to you as seconds instead, in which case you will need to convert it to miliseconds or change the above funciton definition.
function timestampPlus(timestamp, milisecondsDifference, toStringFunc = Date.prototype.toString) {
const date = new Date(timestamp);
const miliseconds = date.getTime();
const newMiliseconds = miliseconds + milisecondsDifference;
const newDate = new Date(newMiliseconds);
const newTimestamp = toStringFunc.call(newDate); // a bit advanced stuff here to let you define once and use whatever kind to string method you want to use, defaults to toString()
return newTimestamp;
}
console.log("new Date(1368435600*1000).toLocaleTimeString(): ", new Date(1368435600*1000).toLocaleTimeString())
console.log("timestampPlus(1368435600*1000, 75*60*1000, Date.prototype.toLocaleString): ", timestampPlus(1368435600*1000, 75*60*1000, Date.prototype.toLocaleTimeString))
Apart from what you need, for last parameter, toStringFunc, your options vary and encompasses all related Date methods, the are on Date.prototype:
toString
toDateString
toTimeString
toLocaleString
toLocaleDateString
toLocaleTimeString
toIsoString
toUTCString
toGMTString
toJSON

Categories