create date object by hours and minutes - javascript

I want to setup a setTimeout function and need to calculate the seconds for the callback. Let's say I want to execute a function at 12:00 (HH-MM) I have to calculate the timespan up to this time. If the time has already passed the next day is relevant.
I get the current date time with new Date()
I know I can calculate the timespan in seconds by using
const difference = dateTimeOne.getTime() - dateTimeTwo.getTime();
const differenceInSeconds = difference / 1000;
Is there a way creating a second date object by passing in the hours and minutes or do I have to calculate it on my own?
An example would be new Date('12:45')

var minutes = 42;
for (var hours = 1; hours < 24; hours+=3) {
var newAlarm = setAlarm(hours, minutes);
out(newAlarm)
}
function out(date) {
var now = new Date()
if (date.getDate() != now.getDate()) {
console.log('tomorrow: ' + date.getHours() + ":" + date.getMinutes())
} else {
console.log('today: ' + date.getHours() + ":" + date.getMinutes())
}
}
function setAlarm(hours, minutes) {
var now = new Date();
var dateTarget = new Date();
dateTarget.setHours(hours)
dateTarget.setMinutes(minutes)
dateTarget.setSeconds(0)
dateTarget.setMilliseconds(0)
if (dateTarget < now) {
dateTarget.setDate(dateTarget.getDate()+1)
}
return dateTarget
}
See this Documentation on MDN

You can manipulate the date and then check whether it is in the past. If it is, just add another day.
const d = new Date();
d.setHours(12);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
if (d < new Date()) {
d.setDate(d.getDate() + 1);
}
console.log(d);

It's possible, but you need to provide the whole time string (which we can get from calling Date() and add the missing part):
const time = '12:45'
const current = new Date()
const dateTimeTwo = new Date(`${current.getFullYear()}-${current.getMonth()+1}-${current.getDate()} ${time}`)

Related

Calculate the difference between two dates and give the result in hh:mm format

date1=2023-01-02T12:22:00
date2=2023-01-03T22:15:00
How could I found the time difference?
function secondsToHMS(secs) {
function z(n){return (n<10?'0':'') + n;}
var sign = secs < 0 ? '-' : '';
secs = Math.abs(secs);
return sign + z(secs/3600 |0) + ':' + z((secs%3600) / 60 |0);
}
var d1 = new Date('2023-01-03T22:15:00');
var d2 = new Date('2023-01-02T12:22:00');
//console.log( secondsToHMS((d1 - d2) / 1000)); // 33:53
You can refer to the answer here: https://stackoverflow.com/a/12193371/9067107
The steps are firstly converting the UTC time via new Date() and calculate the different by date1 - date2 and get the Hours / Minutes different.
Lets assume you want to have HH:mm format in string
let date1 = new Date('2023-01-02T12:22:00')
let date2 = new Date('2023-01-03T22:15:00')
let diff = new Date(date2 - date1)
let diffInHoursMinutes = `${diff.getHours()}:${diff.getMinutes()}`

js different variable same value

Currently i'm facing the following problem. In my JavaScript code, i have a function, which should calculate the weeks from now, to a given timestamp. The problem is, that the the first value has the same Value as another variable with another name. The code:
let myAppointment = event.data.toTime;
console.log(myAppointment);
let currentDate = new Date(Date.now());
let currentTime = (convertStringDateToDate(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), 0,0,0,0)).getTime();
let appointmentStartDate = new Date(myAppointment.getStart());
console.log(appointmentStartDate);
console.log(currentDate);
let appointmentStartTime = (convertStringDateToDate(appointmentStartDate.getFullYear(), appointmentStartDate.getMonth(), appointmentStartDate.getDate(),0,0,0,0)).getTime();
console.log('AppointmentStartTime : ' + appointmentStartTime);
console.log('CurrentTime: ' + currentTime);
let timeskip = appointmentStartTime - currentTime;
console.log(timeskip + ' timeskip / 604800000 = ' + (timeskip / 604800000));
skips = timeskip / 604800000;
await displayCalendar(document.getElementById('wrapper'));
console.log(skips);
if(skips < 0){
skips = Math.floor(skips);
if(Math.abs(skips) != 1){
navigateBackward(skips);
}
}else{
skips = Math.floor(skips);
if(Math.abs(skips) != 1){
navigateForward(skips);
}
}
cleanTable();
displayAppointments();
});
//i think this function may be interesting too, but the error can't occur from here
function
convertStringDateToDate(year,month,day,hours,minutes,seconds,milliseconds){
let date = new Date();
date.setFullYear(year);
date.setMonth(month);
date.setDate(day);
date.setHours(hours);
date.setMinutes(minutes);
date.setSeconds(seconds);
date.setMilliseconds(milliseconds);
return date;
}
The function from let myAppointment = ... Leads to the following console output
The problem lies here:
let appointmentStartTime = (convertStringDateToDate(appointmentStartDate.getFullYear(), appointmentStartDate.getMonth(), appointmentStartDate.getDate(),0,0,0,0)).getTime();
You set the hours, minutes, seconds all to zero - effectively turning your start date to the same value as today's date.
Note that in your particular example, currentDate and appointmentStartDate share the same year, month, and date. When you call let currentTime = (convertStringDateToDate(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), 0,0,0,0)).getTime();
, you should replace 0,0,0,0 with correct values for both currentTime and appointStartTime.
To make your coding style consistent, you can use date.getHours(), date.getMinutes(), date.getSeconds(), and date.getMilliseconds() to replace those four zeroes.
Also, if you want to shorten your code, you can get rid of convertStringDateToDate() and merely call getTime() on currentDate and appointStartDate.
let currentDate = new Date();
let currentTime = (convertStringDateToDate(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), currentDate.getHours(),currentDate.getMinutes(),currentDate.getSeconds(),currentDate.getMilliseconds())).getTime();
console.log(currentTime); // 1537309553647
console.log(currentDate.getTime()); // 1537309553647

Timestamp difference in seconds

I need difference of two timestamp in seconds. But when calculate it gave wrongly. How to calculate the seconds from difference of two timestamp? Thanks in advance.
Here,
First timestamp = 20180104113612
Second timestamp = 20180104113954
Difference = First timestamp - Second timestamp
It results as 342. But actually it should be 222. So please anyone help to find the difference in seconds?
You need to parse out year, month, day, hour, minutes and seconds from your date and create a date object and then subtract both dates to get the difference.
var firstTimestamp = 20180104113612,
secondTimestamp = 20180104113954,
getDate = (time) => {
time = time.toString();
var year = time.substring(0,4),
month = time.substring(4,6),
day = time.substring(6,8),
hour = time.substring(8,10),
minutes = time.substring(10,12),
seconds = time.substring(12,14);
return new Date(year, month, day, hour, minutes, seconds);
},
getTimeDifference = (firstTime, secondTime) => {
return Math.floor((getDate(secondTime) - getDate(firstTime))/1000);
};
console.log(getTimeDifference(firstTimestamp, secondTimestamp));
Try this
let startDate = new Date();
let endDate = new Date();
let differenceInSecond = (endDate - startDate) / 1000; //since it's originally in milliseconds
first you have to format your date in proper format something like this. "2018-01-04T11:36:12";
for formatting you can use make some function like this
function getFormat(dateString) {
var txt = dateString.slice(0, 4)
+ "-"
+ dateString.slice(4, 6)
+ "-"
+dateString.slice(6,8)
+"T"
+dateString.slice(8,10)
+":"
+dateString.slice(10,12)
+":"
+dateString.slice(12,14);
return txt;
}
and then convert it into javascript Date object.
const First_timestamp = 20180104113612;
const Second_timestamp = 20180104113954;
const FirstDate = new Date(getFormat(First_timestamp.toString()));
const SecondDate = new Date(getFormat(Second_timestamp.toString()));
const TimeDiffInSeconds = (SecondDate.getTime() - FirstDate.getTime()) / 1000;

take a date string, add a class to span if expiration date is less than 2 weeks from now

i've been stuck on this problem for a while now and I am ready to pull my hair out :). I have to add a class to a span if a campaign date is expiring in 2 weeks or less. The date retrieved is a string in the following format
07/26/2017
when I run this function, I am passing the datestring as an argument since the method will be attached to the var which holds the string. But for whatever reason this logic isn't working. Am I totally screwing this up? It's failing silently somewhere. Thank you. I know it should be easy but I am caught in a loop.
campMethods.EndDateAlert = function (dateString) {
var currentDate = new Date ();
var twoWeeks = new Date ();
twoWeeks.setDate(currentDate.getDate() + 14)
var $EndDateSpan = $('.campaign-end-date');
if (dateString <= twoWeeks) {
$EndDateSpan.addClass('red');
}
return dateString;
};
You can do that with some Math. The key is, 2 weeks = 14 days.
Here is Pure Javascript example for you:
var date = "07/26/2017".split("/");
var formatedDate = (date[2] + '' + date[0] + '' + date[1]);
var currentDate = new Date();
var today = currentDate.getFullYear() +''+ ("0" + (currentDate.getMonth() + 1)).slice(-2)+''+("0" + currentDate.getDate()).slice(-2);
var compareDay = formatedDate - today;
if(compareDay < 14){// 14 day = 2 week
// do something for less than 2 weeks
console.log('Less than 2 weeks will be expired');
} else {
// also can do something
console.log('more than 2 weeks will be expired.');
}
Javascript Date Reference
Try comparing milliseconds of the dates.
We know that there are 1000 * 60 * 60 * 24 * 14 = 1209600000 milliseconds in two weeks, knowing this we can add 1209600000ms to the current date and compare this to the milliseconds of the due date.
let dueDate = new Date('07/26/2017');
if(Date.now() + 1209600000 > dueDate.getMilliseconds()){
//do stuff
}

Check if time difference is less than 45 mins and run function - AngularJS

This is an easy thing to do in PHP with code like this;
if (strtotime($given_time) >= time()+300) echo "You are online";
But can't find anything on SO to do exactly this in javascript.
I want to check if the difference between a given time and the current time is less than 45mins
For instance
$scope.given_time = "14:10:00"
$scope.current_time = new Date();
I'm only concerned with the time part. I need to extract time part from new Date(); and then compare.
Then this should be true
How can I achieve this with Javascript:
if ($scope.given_time - $scope.current_time < 45 minutes) {
// do something
}
Javascript uses unix timestamps in milliseconds, so it is similar to the output of strtotime (which uses seconds).
var date = new Date();
Then you'll need to do the calculation from milliseconds. (Minutes * 60 * 1000)
You can also use date.parse() to parse a string to milliseconds, just like strtotime() in PHP does to seconds.
In full:
var date = new Date();
var last = new Date('Previous Date'); // or a previous millisecond timestamp
if ( ( date - last ) > ( 45 * 60 * 1000 ) ) {
// do something
}
You could use a static date to compare just time, this is exactly what strtotime does if you exclude the date:
var last = new Date('1/1/70 14:10:00');
var date = new Date('1/1/70 14:30:00');
However, this approach will fail if you're trying to compare time that cross over day boundaries.
Try this:
function checkTime(time) {
var date = new Date();
var date1 = new Date((date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + time);
var minutes = (date1.getTime() - date.getTime()) / (60 * 1000);
if (minutes > 45 || (minutes < 0 && minutes > -1395)) {
// greater than 45 is todays time is above 45 minutes
// less than 0 means the next available time will be tomorrow and the greater than -1395 means it will be more than 45 minutes from now into tomorrow
document.write(time + ': true<br />');
} else {
document.write(time + ': false<br />');
}
}
checkTime("14:10:00");
checkTime("16:30:00");
checkTime("17:10:00");
There's a JavaScript method called getMinutes(); you can use to get only the minutes and compare.
Your code should look something like:
var received_time = "14:10:00".split(':');
var minute = '';
if(received_time.length === 3) {
minute = parseInt(received_time[1], 10);
}
$scope.given_time = minute;
var the_time = new Date();
$scope.current_time = the_time.getMinutes();
And you now can do your thing:
if ($scope.given_time - $scope.current_time < 45 minutes) {
// do something
}
Using a library like moment.js you can simply diff the two times.
var $log = $("#log");
/* Difference between just times */
$log.append("Difference between times\n");
var givenTime = moment("14:10:00", "HH:mm:ss");
var minutesPassed = moment("14:30:00", "HH:mm:ss").diff(givenTime, "minutes");
$log.append("Minutes passed: " + minutesPassed + "\n");
if (minutesPassed < 45) {
$log.append(minutesPassed + " minutes have elapsed. Event Triggered." + "\n");
}
/* Better: Difference between times that have dates attached to them and cross a day boundary. */
$log.append("\n\nDifference between dates with times\n");
givenTime = moment("2015-12-03 23:33:00");
minutesPassed = moment("2015-12-04 00:14:00").diff(givenTime, "minutes");
$log.append("Minutes passed: " + minutesPassed + "\n");
if (minutesPassed < 45) {
$log.append(minutesPassed + " minutes have elapsed. Event Triggered." + "\n");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://momentjs.com/downloads/moment.js"></script>
<p>Results:</p>
<hr>
<pre id="log"></pre>
<hr>
Caveat: If the given time is yesterday such as 11:30pm and the current time is 12:10am then you will get the wrong result. You'd want to use a date with the time if this type of thing is an issue for your use case.
The moment.js documentation
http://momentjs.com/docs/
Angular directive for moment documentation
https://github.com/urish/angular-moment/blob/master/README.md

Categories

Resources