javascript - get the date of next day in week? - javascript

how do I get, for example, the date of next monday and the time 5:30PM, and calculate the difference between current date and time and that date and time?
if I run it now at 8/28/2020 17:35, it should give me 8/31/2020 17:30 and the difference 2 days 23 hours 55 minutes.

I hope this help:
// takes dayIndex from Sunday(0) to Saturday(6)
const getNextDay = (dayIndex) => {
const today = new Date();
today.setDate(
today.getDate() + ((dayIndex - 1 - today.getDay() + 7) % 7) + 1
);
today.setHours(17, 30, 00);
return today;
};
const getTimeleft = (dateNow, dateFuture) => {
let seconds = Math.floor((dateFuture - dateNow) / 1000);
let minutes = Math.floor(seconds / 60);
let hours = Math.floor(minutes / 60);
let 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;
return `${days} days ${hours} hours ${minutes} minutes`;
};
const now = new Date();
const nextMonday = getNextDay(1);
const timeleft = getTimeleft(now, nextMonday);
console.log(nextMonday.toLocaleString());
console.log(timeleft);

You could use moment.js, it's a very useful library when it comes to dates:
<script src="https://momentjs.com/downloads/moment.js"></script>
<script>
const today = moment();
const nextMonday = moment().add(1, 'weeks').isoWeekday(1);
nextMonday.set({'hour': 17, 'minute': 30, 'seconds': 0});
console.log(nextMonday.toString());
const duration = moment.duration(nextMonday.diff(today));
const days = duration.asDays();
const hours = (days - Math.floor(days)) * 24;
const minutes = (hours - Math.floor(hours)) * 60;
console.log("days", Math.floor(days));
console.log("hours", Math.floor(hours));
console.log("minutes", Math.floor(minutes));
</script>

Here is the working example:
function nextWeekMonday(date)
{
var diff = date.getDate() - date.getDay() + (date.getDay() === 0 ? -6 : 1);
var currWeekMonday = new Date(date.setDate(diff));
return new Date(currWeekMonday.getTime() + 7 * 24 * 60 * 60 * 1000);
}
function getDateDifference(current, future) {
// get total seconds between the times
var delta = Math.abs(future - current) / 1000;
// calculate (and subtract) whole days
var days = Math.floor(delta / 86400);
delta -= days * 86400;
// calculate (and subtract) whole hours
var hours = Math.floor(delta / 3600) % 24;
delta -= hours * 3600;
// calculate (and subtract) whole minutes
var minutes = Math.floor(delta / 60) % 60;
delta -= minutes * 60;
// what's left is seconds
var seconds = delta % 60;
return `${days} Days, ${hours} Hours, ${minutes} Minutes, ${seconds} Seconds`;
}
var curr = new Date; // get current date
var nextMonday = nextWeekMonday(curr);
console.log(getDateDifference(curr, nextMonday));

Related

Javascript output issue when parsing mysql timestamp

I'm attempting to display how much time is left, based on a mysql timestamp. For some reason the output is -1 days, 23 hours, 59 minutes, 59 seconds.
<script type="text/javascript">
function update(datetime = "2021-07-15 20:24:42") {
timeleft = new Date(datetime);
now = new Date();
secs = (timeleft - now) / 1000;
days = Math.floor(secs / (3600 * 24));
hours = Math.floor((secs - (days * (3600 * 24)))/3600);
minutes = Math.floor((secs - (days * (3600 * 24)) - (hours * 3600)) / 60);
seconds = Math.floor(secs - (days * (3600 * 24)) - (hours * 3600) - (minutes * 60));
if (seconds < 0) {
days = 0;
hours = 0;
minutes = 0;
seconds = 0;
}
return days+' days, '+ hours+' hours, '+minutes+' minutes, '+seconds+' seconds';
}
// time is pulled from database, but plugged in manually
member = Date("06-08-21 16:06:37");
alert("Left: "+update(member));
</script>
Any info would be appreciated
1) You can use new Date() to create a new instance and pass a valid date.
2) You are using dd-mm-yy format so you should make it valid because if you pass it directly then it will convert the date
member = new Date(dateString); // 2021-06-08T10:36:37.000Z
i.e Date is 08, month = 06, So you have to swap the date and month value before getting the date instance from new Date()
const dateString = "06-08-21 16:06:37".replace(
/(\d\d)-(\d\d)-(\d\d \d\d:\d\d:\d\d)/,
`$2-$1-$3`
);
function update(datetime = "2021-07-15 20:24:42") {
timeleft = new Date(datetime);
now = new Date();
secs = (timeleft - now) / 1000;
days = Math.floor(secs / (3600 * 24));
hours = Math.floor((secs - days * (3600 * 24)) / 3600);
minutes = Math.floor((secs - days * (3600 * 24) - hours * 3600) / 60);
seconds = Math.floor(secs - days * (3600 * 24) - hours * 3600 - minutes * 60);
if (seconds < 0) {
days = 0;
hours = 0;
minutes = 0;
seconds = 0;
}
return (
days +
" days, " +
hours +
" hours, " +
minutes +
" minutes, " +
seconds +
" seconds"
);
}
// time is pulled from database, but plugged in manually
const dateString = "06-08-21 16:06:37".replace(
/(\d\d)-(\d\d)-(\d\d \d\d:\d\d:\d\d)/,
`$2-$1-$3`
);
member = new Date(dateString);
console.log("Left: " + update(member));

How to convert milliseconds into Days/hours/minutes

I am calculating the hours,minutes using the milliseconds. Below is mycode
function getDuration(milli){
let minutes = Math.floor(milli / 60000);
let hours = Math.round(minutes / 60);
}
I want to display the user the time as 'Days' if hours > 24 , 'minutes' if minute < 60. How can i implement it in template string in the following format
setHtml('Duration', `${getDuration(user[0].milli_seconds)} <span id="days">Hours</span> <span>Minutes</span>`);
You could return it as an object which returns days, hours or minutes depending on what is there.
function getDuration(milli){
let minutes = Math.floor(milli / 60000);
let hours = Math.round(minutes / 60);
let days = Math.round(hours / 24);
return (
(days && {value: days, unit: 'days'}) ||
(hours && {value: hours, unit: 'hours'}) ||
{value: minutes, unit: 'minutes'}
)
};
var tDuration = getDuration(23456576210);
console.log(tDuration.value + ': ' + tDuration.unit);
Original version:
function getDuration(milli){
let minutes = Math.floor(milli / 60000);
let hours = Math.round(minutes / 60);
let days = Math.round(hours / 24);
return (
(days && {days: days}) ||
(hours && {hours: hours}) ||
{minutes: minutes}
)
};
var tDuration = getDuration(23456576210);
console.log(tDuration);
Calculate days first , then hours and minutes
function convertToDays(milliSeconds){
let days = Math.floor(milliSeconds/(86400 * 1000));
milliSeconds -= days*(86400*1000);
let hours = Math.floor(milliSeconds/(60 * 60 * 1000 ));
milliSeconds -= hours * (60 * 60 * 1000);
let minutes = Math.floor(milliSeconds/(60 * 1000));
return {
days,hours,minutes
}
}
console.log(convertToDays(8640000));

timer data start for next week

function countDown(){
// Set the date we're counting down to
var countDownDate = new Date("july 11, 2017 10:19:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
countDownDate = new Date("july 18, 2017 10:19:00").getTime();
}
}, 1000);
}
countDown();
what I want to reach is the every week the timer will start count to the next week.
I have something that start every week in the same day and in the same hour.
I don't want to rewrite the code every week :/
Thank you.
so why so much calculation is needed just to calculate how many seconds are remaining to start of next week? for example I am writing a sample code to calculate it.
function distranceToNextWeekStartInSeconds() {
var now = new Date()
var dayDiff = 7 - now.getDay();
var startOfNextWeek = new Date(now.valueOf());
startOfNextWeek.setDate(now.getDate() + dayDiff);
startOfNextWeek.setHours(0);
startOfNextWeek.setMinutes(0);
startOfNextWeek.setSeconds(0);
return Math.floor((startOfNextWeek - now) / 1000);
}
console.log('Seconds remaining to next week start: ' + distranceToNextWeekStartInSeconds())
and you can simply call this function inside your timer for a live calculation and display purpose, That's It.
I assumed you wanted to count down to every next tuesday at 10:19:00.
I'm too lazy right now to test every cases, ut I think it should work.
function getNextTuesday() {
// Get the date from now
var date = new Date();
// Set target hour/minute/seconds
date.setHours(10);
date.setMinutes(19);
date.setSeconds(0);
// Seek for the next tuesday
var actualDay = date.getDay();
var targetDay = 2; //Tuesday
// diff will give us the day span between today and the next tuesday
var diff = targetDay - actualDay;
// If the diff is less than 0 (we're sunday or monday, or we fall on the exact day, minutes after the target hour) then add a week
if (diff < 0 || (date.getTime() - new Date().getTime()) <= 0) {
diff += 7;
}
// Finally add the day span to the current date
date.setDate(date.getDate() + diff);
return date;
}
function countDown() {
// Set the date we're counting down to
var countDownDate = getNextTuesday();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
if (distance < 0) {
// If the count down is over, write some text
document.getElementById("demo").innerHTML = 'IT\'S HAPPENING !';
countDownDate = getNextTuesday();
} else {
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
}
}, 1000);
}
countDown();
<div id="demo"></div>

jQuery Timer Days/Months/Years

I'm creating a countdown Timer that counts down to a date that is inputted in the code for example April 6th 2016.
So far I have got it to output the amount of days, but I cannot figure out how to do the amount of months and years. I do not need Hours Minutes or seconds!
code in app.js
$(document).ready(function(){
eventTime = '6 April 2016';
})
Code in countdown.js:
(function($){
$.fn.countdown = function(options) {
var settings = { date: null };
if (options) {
$.extend(settings, options);
}
this_sel = $(this);
function count_exec () {
eventDate = Date.parse(settings['date']) / 1000;
currentDate = Math.floor($.now () / 1000);
seconds = eventDate - currentDate
days = Math.floor(seconds / (60 * 60 * 24));
months = Math.floor(seconds / (60 * 60 * 12));
alert(days);
}
count_exec();
}
})(jQuery);
Given two dates, use the following code to compute their difference in milliseconds, then in seconds, minutes, hours, days and months:
var currentDate = new Date();
var eventDate = new Date(2016, 3, 6); // months start from 0
var milliseconds = eventDate.getTime() - currentDate.getTime();
var seconds = parseInt(milliseconds / 1000);
var minutes = parseInt(seconds / 60);
var hours = parseInt(minutes / 60);
var days = parseInt(hours / 24);
var months = parseInt(days / 30);
seconds -= minutes * 60;
minutes -= hours * 60;
hours -= days * 24;
days -= months * 30;
For a more accurate difference in months, take a look at Difference in Months between two dates in JavaScript.

How can I convert milliseconds to "hhmmss" format using javascript?

I am using javascript Date object trying to convert millisecond to how many hour, minute and second it is.
I have the currentTime in milliseconds
var currentTime = new Date().getTime()
and I have futureTime in milliseconds
var futureTime = '1432342800000'
I wanted to get difference in millisecond
var timeDiff = futureTime - currentTime
the the timeDiff was
timeDiff = '2568370873'
I want to know how many hours, minutes, seconds it is.
Could anyone help?
const secDiff = timeDiff / 1000; //in s
const minDiff = timeDiff / 60 / 1000; //in minutes
const hDiff = timeDiff / 3600 / 1000; //in hours
updated
function msToHMS( ms ) {
// 1- Convert to seconds:
let seconds = ms / 1000;
// 2- Extract hours:
const hours = parseInt( seconds / 3600 ); // 3,600 seconds in 1 hour
seconds = seconds % 3600; // seconds remaining after extracting hours
// 3- Extract minutes:
const minutes = parseInt( seconds / 60 ); // 60 seconds in 1 minute
// 4- Keep only seconds not extracted to minutes:
seconds = seconds % 60;
alert( hours+":"+minutes+":"+seconds);
}
const timespan = 2568370873;
msToHMS( timespan );
Demo
If you are confident that the period will always be less than a day you could use this one-liner:
new Date(timeDiff).toISOString().slice(11,19) // HH:MM:SS
N.B. This will be wrong if timeDiff is greater than a day.
Convert ms to hh:mm:ss
function millisecondsToHuman(ms) {
const seconds = Math.floor((ms / 1000) % 60);
const minutes = Math.floor((ms / 1000 / 60) % 60);
const hours = Math.floor((ms / 1000 / 3600 ) % 24)
const humanized = [
pad(hours.toString(), 2),
pad(minutes.toString(), 2),
pad(seconds.toString(), 2),
].join(':');
return humanized;
}
=
function msToHMS( duration ) {
var milliseconds = parseInt((duration % 1000) / 100),
seconds = parseInt((duration / 1000) % 60),
minutes = parseInt((duration / (1000 * 60)) % 60),
hours = parseInt((duration / (1000 * 60 * 60)) % 24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds ;
}
Converts milliseconds to a string in the format hh:mm:ss. Here's my version:
function HHMMSSFromMilliseconds(ms) {
// 1- Convert to seconds:
var seconds = ms / 1000;
// 2- Extract hours:
var hours = parseInt(seconds / 3600); // 3600 seconds in 1 hour
seconds = parseInt(seconds % 3600); // extract the remaining seconds after extracting hours
// 3- Extract minutes:
var minutes = parseInt(seconds / 60); // 60 seconds in 1 minute
// 4- Keep only seconds not extracted to minutes:
seconds = parseInt(seconds % 60);
// 5 - Format so it shows a leading zero if needed
let hoursStr = ("00" + hours).slice(-2);
let minutesStr = ("00" + minutes).slice(-2);
let secondsStr = ("00" + seconds).slice(-2);
return hoursStr + ":" + minutesStr + ":" + secondsStr
}
let timespan = 23570 * 1000;
let formattedTime = HHMMSSFromMilliseconds(timespan);
console.log(formattedTime);
Convert millis to DD(days):HH:MM:SS
function formatTime(timeMS) {
const [MS_IN_SEC, SEC_IN_DAY, SEC_IN_HOUR, SEC_IN_MIN] = [1000, 86400, 3600, 60];
let seconds = Math.round(Math.abs(timeMS) / MS_IN_SEC);
const days = Math.floor(seconds / SEC_IN_DAY);
seconds = Math.floor(seconds % SEC_IN_DAY);
const hours = Math.floor(seconds / SEC_IN_HOUR);
seconds = Math.floor(seconds % SEC_IN_HOUR);
const minutes = Math.floor(seconds / SEC_IN_MIN);
seconds = Math.floor(seconds % SEC_IN_MIN);
const [dd, hh, mm, ss] = [days, hours, minutes, seconds]
.map(item => item < 10 ? '0' + item : item.toString());
return dd + ':' + hh + ':' + mm + ':' + ss;
}
The difference in time is in milliseconds:
Get time difference between two dates in seconds
to get the difference you have to use math.floor()
http://www.w3schools.com/jsref/jsref_floor.asp
var secDiff = Math.floor(timeDiff / 1000); //in s
var minDiff = Math.floor(timeDiff / 60 / 1000); //in minutes
var hDiff = Math.floor(timeDiff / 3600 / 1000); //in hours
var timediff = futureTime - currentTime
long seconds = (long) (timediff / 1000) % 60 ;
long minutes = (long) ((timediff / (1000*60)) % 60);
long hours = (long) ((timediff / (1000*60*60)) % 24);
if(hours>0)
time = hours+" hrs : "+minutes+" mins";
else if(minutes>0)
time = minutes+" mins";
else if(seconds>0)
time = seconds+" secs";
Here is a simple function
function simplifiedMilliseconds(milliseconds) {
const totalSeconds = parseInt(Math.floor(milliseconds / 1000));
const totalMinutes = parseInt(Math.floor(totalSeconds / 60));
const totalHours = parseInt(Math.floor(totalMinutes / 60));
const days = parseInt(Math.floor(totalHours / 24));
const seconds = parseInt(totalSeconds % 60);
const minutes = parseInt(totalMinutes % 60);
const hours = parseInt(totalHours % 24);
let time = '1s';
if (days > 0) {
time = `${days}d:${hours}h:${minutes}m:${seconds}s`;
} else if (hours > 0) {
time = `${hours}h:${minutes}m:${seconds}s`;
} else if (minutes > 0) {
time = `${minutes}m:${seconds}s`;
} else if (seconds > 0) {
time = `${seconds}s`;
}
return time;
}

Categories

Resources