Date and Time tips
Advance the time with x seconds
This example shows how you can advance the time with x seconds.
var now;
now = new Date('2023-01-01 23:59:55');
alert(now.getMinutes() + ':' + now.getSeconds());
now.setSeconds(now.getSeconds() + 10);
alert(now.getMinutes() + ':0' + now.getSeconds());
alert(now)
Using now.setSeconds() we add 10 seconds to the current time in this example. In this particular case the time will change from 23 hour 59 minutes and 5 seconds to 5 seconds after midnight and therefore the date will alter automatically.
This example shows how you can advance the time with x seconds.
var now;
now = new Date('2023-01-01 23:59:55');
alert(now.getMinutes() + ':' + now.getSeconds());
now.setSeconds(now.getSeconds() + 10);
alert(now.getMinutes() + ':0' + now.getSeconds());
alert(now)
Using now.setSeconds() we add 10 seconds to the current time in this example. In this particular case the time will change from 23 hour 59 minutes and 5 seconds to 5 seconds after midnight and therefore the date will alter automatically.
Advance the time with 30 minutes
If you want to set the time in a variable 30 minutes forward you can do that with setMinutes() and getMinutes like the next snippet shows.
var testdate = new Date();
testdate.setMinutes( testdate.getMinutes() + 30 );
alert( testdate );
You can use the same method with -30 to set the time 30 minutes back.
If you want to set the time in a variable 30 minutes forward you can do that with setMinutes() and getMinutes like the next snippet shows.
var testdate = new Date();
testdate.setMinutes( testdate.getMinutes() + 30 );
alert( testdate );
You can use the same method with -30 to set the time 30 minutes back.
Advance the time by one day
If you need tomorrows date you can do that by adding 1 to todays date in a variable.
var now = new Date();
var tomorrow = new Date();
tomorrow.setDate(nu.getDate() + 1);
alert('Now: ' + now);
alert('Tomorrow: ' + tomorrow);
If you need tomorrows date you can do that by adding 1 to todays date in a variable.
var now = new Date();
var tomorrow = new Date();
tomorrow.setDate(nu.getDate() + 1);
alert('Now: ' + now);
alert('Tomorrow: ' + tomorrow);
Change 24 hours notation to 12 hours
To change 24 hours klok notation to 12 hours notation we just have to take the hours modulus 12.
var today = new Date();
var hour = today.getHours();
alert(hour);
alert(hour %12);
Advance the time with 30 minutes
If you want to set the time in a variable 30 minutes forward you can do that
with setMinutes() and getMinutes like the next snippet shows.
var testdate = new Date();
testdate.setMinutes( testdate.getMinutes() + 30 );
alert( testdate );
You can use the same method with -30 to set the time 30 minutes back.
If you want to set the time in a variable 30 minutes forward you can do that
with setMinutes() and getMinutes like the next snippet shows.
var testdate = new Date();
testdate.setMinutes( testdate.getMinutes() + 30 );
alert( testdate );
You can use the same method with -30 to set the time 30 minutes back.
Comparing dates
Somewhere in a program there are 2 variables which contain a date and we want to compare them.
var date1 = "09/12/2020"; // 12 september
van date2 = "08/05/2020"; // 5 august
To compare these dates we have to transform them into Date Objects. This can be done using new Date().
date1 = new Date(date1);
date2 = new Date(date2);
Now we can easily compare these dates:
datum1 > datum2; //true
datum2 < datum1; //false
datum1 >= datum2; //true
datum1 <= datum2; //false
datum1 == datum2; // false
Comparing dates
Somewhere in a program there are 2 variables which contain a date and we want to compare them.
var date1 = "09/12/2020"; // 12 september
van date2 = "08/05/2020"; // 5 august
To compare these dates we have to transform them into Date Objects. This can be done using new Date().
date1 = new Date(date1);
date2 = new Date(date2);
Now we can easily compare these dates:
datum1 > datum2; //true
datum2 < datum1; //false
datum1 >= datum2; //true
datum1 <= datum2; //false
datum1 == datum2; // false
Somewhere in a program there are 2 variables which contain a date and we want to compare them.
var date1 = "09/12/2020"; // 12 september
van date2 = "08/05/2020"; // 5 august
To compare these dates we have to transform them into Date Objects. This can be done using new Date().
date1 = new Date(date1);
date2 = new Date(date2);
Now we can easily compare these dates:
datum1 > datum2; //true
datum2 < datum1; //false
datum1 >= datum2; //true
datum1 <= datum2; //false
datum1 == datum2; // false
Comparing dates 2
To compare two dates we can not simply use == or ===
var d1 = new Date("09/22/2020"); // 22 september 2020
var d2 = new Date("09/22/2020"); // 22 september 2020
alert (d1 === d2);
The above alert will give "false" the right way to do it is:
alert (d1.toString() === d2.toString());
Comparing dates 3
Comparing dates may lead to false outcome when the time is taken into account. The dates may be the same but the time paart may differ. Set the time to zero to compare the dates. The following example shows how to achieve this.
var date1, date2
date1 = new Date();
date1.setHours(0,0,0,0);
alert(date1);
date2 = new Date( "Jun 18, 2021" );
alert(date2);
if (date1.getTime() === date2.getTime())
{
alert("The dates are equal.");
}
else
}
alert("The dates differ.");
}
Convert seconds to hours and minutes
To convert a large number of seconds into hours, minutes and seconds you can use the next code.
var date = new Date(0);
date.setSeconds(3600);
var time = date.toISOString().substr(11, 8);
console.log(time)
To convert a large number of seconds into hours, minutes and seconds you can use the next code.
var date = new Date(0);
date.setSeconds(3600);
var time = date.toISOString().substr(11, 8);
console.log(time)
Convert a certain time to seconds
If you have a variable which is the time in Hour, minutes, seconds and you need to know how many seconds this is you can get that number as follows.
var time = "2:1:20";
var timearray = time.split(":");
alert("The time is = " + timearray);
var seconds = (+timearray[0]) * 60 * 60 + (+timearray[1]) * 60 + (+timearray[2]);
alert("The total number of seconds = "+seconds);
The time is put into a variable with the name time in the hh:mm:ss format. The time variable is split into an array and each element is converted to the number of seconds.
Convert seconds to hours and minutes
In IOT projects the time that a sensor measures its data is often registered in seconds. The next function converts the number of seconds to hours and minutes.
var totsecs = 3722;
function secstohour()
{
var hours = parseInt(totsecs / 3600);
var minutes = parseInt((totsecs - (hours * 3600)) / 60);
var time = hours + " hour and " + minutes + " minutes"
return time;
};
alert(secstohour(totsecs));
The total number of seconds (totsecs) is divided by 3600 (the number of seconds in an hour) and the rest is divided by 60 to get the number of minutes. Both figures are made into integers to avoid getting decimals.
Create a random date
The next snippet shows how to create a random date between a start date an today's date.
function makedate(start, end) {
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}
createddate = makedate(new Date(2000,0,0), new Date())
alert(createddate)
In this example the start date is the year 2000 but you can replace it by any date of your choice. You can also change the second date to create a boundary like this:
createddate = makedate(new Date(2000,0,0), new Date(2001,0,0))
alert(createddate)
The next snippet shows how to create a random date between a start date an today's date.
function makedate(start, end) {
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}
createddate = makedate(new Date(2000,0,0), new Date())
alert(createddate)
In this example the start date is the year 2000 but you can replace it by any date of your choice. You can also change the second date to create a boundary like this:
createddate = makedate(new Date(2000,0,0), new Date(2001,0,0))
alert(createddate)
Each day of the week another function or value or picture
You can change the value of a variable, execute another function, show a different text or picture depending on the day of the week. To achieve this use the next snippet.
var nowday=new Date().getDay()
if (nowday==1)
{
alert (1)
}
else if (nowday==2)
{
alert(2)
}
else if (nowday==3)
{
alert(3)
}
...
else if (nowday==7)
{
alert(7)
}
else
{
alert("fout")
}
new Date().getDay() gives us the number of the day of the week. Dyas are numbered from 1 to 7. The if -else if lines show therefore every day another alert which can be replaced by changing a value, another function or replace a picture with another picture on your site.
Find the first and last day of the month
You can find the first and last day using the next code.
var now = new Date();
var firstday = new Date(now.getFullYear(), now.getMonth(), 1);
alert(firstday);
var lastday = new Date(now.getFullYear(), now.getMonth() + 1, 0);
alert (lastday);
The first day of the month is found by setting the number of the day to 1. The last day is found by adding 1 to the number of the month and setting the number of the day to 0.
Generate a random new date from a starting date
If you need to generate a random date between a starting date and en anding date you can use the next snippet.
start = new Date(2023, 0,1)
end = new Date(2060, 0, 1)
randdate = (start.getTime() + Math.random() * (end.getTime() - start.getTime()))
randdate = new Date(randdate)
alert(randdate)
If you need to generate a random date between a starting date and en anding date you can use the next snippet.
start = new Date(2023, 0,1)
end = new Date(2060, 0, 1)
randdate = (start.getTime() + Math.random() * (end.getTime() - start.getTime()))
randdate = new Date(randdate)
alert(randdate)
Get the users timezone
If you are working with date and time related programs it is important to get the users timezone. Here is how to get the information/
zone = Intl.DateTimeFormat().resolvedOptions().timeZone
alert(zone)
If you are working with date and time related programs it is important to get the users timezone. Here is how to get the information/
zone = Intl.DateTimeFormat().resolvedOptions().timeZone
alert(zone)
Give me the date of tomorrow or 20 days from now
Dates are often used in Javascript. Be it for keeping an agenda, keeping dates for customer orders or lists with temperatures. Working with dates often requires to get a date in the future or in the past. The next function calculates a date by adding or subtracting a number of days.
function calcdate(from, amount)
{
var newdate = new Date(from);
newdate.setDate(newdate.getDate() + amount);
return newdate;
}
var newdate = calcdate("09/20/2020",+150);
alert(newdate);
alert(newdate.getDate() + " " + (newdate.getMonth()+1) + " " + newdate.getFullYear());
You need to use newdate.getMonth()+1 because the date index starts at 0
Give me the name of the month
Using new.Date().getMonth() we can het the number of the month. If you need the name you will have to put the names in an array and use the number as the index. here is an example.
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var today = new Date();
alert(today.getMonth())
var name = months[today.getMonth()];
alert(name)
Using new.Date().getMonth() we can het the number of the month. If you need the name you will have to put the names in an array and use the number as the index. here is an example.
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var today = new Date();
alert(today.getMonth())
var name = months[today.getMonth()];
alert(name)
Give me yesterdays date or that of 20 days ago
We can use the tip "Give me the date of tomorrow or 20 days from now" the same way to test for yesrterdays date or that of x days ago. The only thing you have to do is in the example:
var newdate = calcdate("09/20/2020",+150)
change into:
var newdate = calcdate("09/20/2020",-150)
Javascript automatically uses the lengths of the months and takes in account wether it is a leap year or not.
Give me the date over 4 months or 3 Year
We will use the formula from the tip: Give me the date of tomorrow or 20 days from now
function calcdate(from, amount)
{
var newdate = new Date(from);
newdate.setDate(newdate.getDate() + amount);
return newdate;
}
To calculate months in the future or past you need to change:
newdate.setDate(newdate.getDate() + amount);
into
newdate.setMonth(newdate.getMonth() + amount);
For calculating with years you need to alter the formula in:
newdate.setFullYear(newdate.getFullyear() + amount);
How many days between two dates
Suppose we have 2 dates. Todays date and August 31 2026. How many days are between those dates.
Start with defining two variables with the dates:
var date1 = new Date();
var date2 = new Date("08/31/2026");
Next step is to calculate the difference between the two dates:
timedif = date2.getTime() - date1.getTime();
Last step is to transform this into days:
daysdif = Math.round(timedif / (1000 *3600 *24));
Math.round makes sure the number is rounded.
The formula 1000 (1 second) * 3600 (60 seconds * 60 minutes) *24 gives 1 day.
How many days between two dates 2
The next script shows how to calculate the number of days between two dates.
You can use this for example to calculate how many days it is till Christmass
The calculation subtracts the tw dates which gives the time in milisecionds.
Divide this by 1000 and that is is difference in seconds. Then there are
86400 seconds in one day.
var firstdate;
var seconddate;
firstdate = new Date();
seconddate = new Date( "Dec 25, 2020" );
var between = Math.abs(firstdate - seconddate);
var days = Math.floor(between / 1000 / 86400);
alert("number of days : "+days;
How many days in a specific month
To find the number of days in a specific month use the new Date function while setting the amount of days to 0. The next example explains this.
var numberdays = (new Date(2020, 2, 0).getDate());
alert(numberdays);
How many months between two days
The following snippet shows how to calculate the number of months between two dates.
function monthsbetween(date1, date2)
{
var d1 = date1, d2 = date2;
if (date1 < date2)
{
d1 = date2;
d2 = date1;
}
var maand = (d1.getFullYear() - d2.getFullYear()) * 12 + (d1.getMonth() - d2.getMonth());
if (d1.getDate() < d2.getDate())
{
--m;
}
return maand;
}
var date1 = new Date("12 May 2020");
var date2 = new Date("12 Jan 2021");
document.write("Months in between = " + monthsbetween(date1,date2));
The test if (date1 < date2) and the following code let the function adjust automatically if date1 is more recent as date2 or the other way around.
The calculation subtracts the two dates and multiplies the outcome by 12 and adds the difference in months.
How many minutes between two dates
The next snippet calculates how many minutes there are between two dates.
function getmins(first, last)
{
return (last - first) / (1000 * 60);
}
howlong = getmins(
new Date('2021-08-17 09:00:00'),
new Date('2021-08-17 10:00:00')
);
alert(howlong)
The calculation is done by subtracting the second date from the first and dividing that by (1000 * 60) as a minute is 60 seconds * 1000 milliseconds.
How many seconds between two dates
The next snippet calculates how many seconds there are between two dates.
function getsecs(first, last)
{
return (last - first) / 1000;
}
howlong = getsecs(
new Date('2021-08-17 09:00:00'),
new Date('2021-08-17 18:00:00')
);
alert(howlong)
How many hours between two days
The next snippet gives a function that calculates the number of hours between two dates.
function hours(first, last)
{
alert((last - first) / (1000 * 60*60));
}
hours(
new Date('2021-08-30'),
new Date('2021-08-31')
);
How many years between two dates
To calculate the number of years between two dates first convert tem both to millisecionds and then divide the number of milliseconds by the number of milliseconds in a year.
var datestring = "2023,02,01"
var dateinmillies = new Date() - new Date(datestring);
var years=Math.floor(dateinmillies/1000/60/60/24/365);
alert(years)
To calculate the number of years between two dates first convert tem both to millisecionds and then divide the number of milliseconds by the number of milliseconds in a year.
var datestring = "2023,02,01"
var dateinmillies = new Date() - new Date(datestring);
var years=Math.floor(dateinmillies/1000/60/60/24/365);
alert(years)
In what quarter do we live
The following snippet has a function that you can ujse to determine in which quarter a date is.
var newmonth = new Date().getMonth()+1
function findquarter()
{
if (newmonth <= 3) {return 1}
else if (newmonth <= 6) {return 2}
else if (newmonth <= 9) {return 3}
else if (newmonth <= 12) {return 4}
}
alert(findquarter(newmonth))
We start with finding the month with new Date().getMonth()+1 Mind that we have to add 1 to the month as months strat with index 0 (january = month 0). Next an if-else test looks in which part of the year the month is.
In which century do we live
To know in what century we live we have to divide the year by 100. If that is an integer (2000) then we have the century. If it is not an integer we need to add 1. In the chapter about numbers you can find how to test if a number is an integer. We are going to use that here.
function testcentury(year)
{
if (year/100 % 1 === 0)
{
return year/100;
}
else
{
return parseInt(year/100, 10)+1;
}
}
var century = testcentury(1885);
alert (century);
In which century do we live 2
Math.ceil() rounds numbers up to the nearest integer. We can use that to determine in an easy way in which century we live.
alert(Math.ceil(1999/100))
Math.ceil() rounds numbers up to the nearest integer. We can use that to determine in an easy way in which century we live.
alert(Math.ceil(1999/100))
Is January first a Sunday ?
To know if January 1 in a certain year is a Sunday you can use the next snippet.
var year = 2017;
var datum = new Date(year, 0, 1);
if ( datum.getDay() === 0 )
{
document.write("January 1 in "+year+" is a Sunday");
}
Using this snippet we can examine any day of the year. Counting of names of the days begins at 0 for Sundays. Counting of months starts with 0 for January.
Is the given day a weekday or in weekend
To know if a given day is a weekday or falls in the weekend we can use the getDay command. This will give us the day in the week in numbers from 0 to 6 where 6 is Saturday and 0 is Sunday.
The next program shows an alert that tells us wether the choosen day is a weekday or is in the weekend.
var date = new Date("2020-09-26");
var day = datum.getDay();
var weekend = (day === 6) || (day === 0);
if(weekend==true)
{
alert("The choosen day is in a weekend");
} else
{
alert("A weekday");
Is this year a leapyear
To test whether a year is a leapyear we need to know if there is a february 29. Set the date to february 29 and if that not exsists in the given year the month will be set to march which has index 2. So we test for index 1 which is february (januari is 0).
function leap(year)
{
return new Date(year, 1, 29).getMonth() === 1;
}
alert(leap(2021));
alert(leap(2020));
Is this year a leapyear
There are several demands for a year to be a leapyear. If it is a full century then it should also be divisible by 100 AND 400. Next to that the year should be divisible by 4. So 1700 is not a leapyear as it is divisible by 100 but not by 400. We can test this by a ternary operator.
function leapyear(year)
{
return (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0);
}
alert(leapyear(2100))
alert(leapyear(2200))
alert(leapyear(2020))
Make a copy of a date
If you need an exact copy of a date you can use the next lines of code.
var now;
var nowcopy;
now = new Date();
var nowcopy = new Date(now.getTime());
alert(nowcopy);
By using getTime() we get the exact time from the original date and copy that into the new variable. This makes sure that we have an exact copy of the date and time.
If you need an exact copy of a date you can use the next lines of code.
var now;
var nowcopy;
now = new Date();
var nowcopy = new Date(now.getTime());
alert(nowcopy);
By using getTime() we get the exact time from the original date and copy that into the new variable. This makes sure that we have an exact copy of the date and time.
Measure how long an action takes
To get a time in milliseconds you can use + new Date() If you put this at the start of a program part and at the end you can measure how long it takes to complete the action. Here is an example snippet that measures the time to calculate 1000.000 square roots.
var start = + new Date();
for (i=0; i<1000000; i++)
{
var dummy = Math.sqrt(i);
}
var end = + new Date();
alert(end - start);t.
To get a time in milliseconds you can use + new Date() If you put this at the start of a program part and at the end you can measure how long it takes to complete the action. Here is an example snippet that measures the time to calculate 1000.000 square roots.
var start = + new Date();
for (i=0; i<1000000; i++)
{
var dummy = Math.sqrt(i);
}
var end = + new Date();
alert(end - start);t.
Put a clock on your screen
The next example shows how to put a clock on your screen. The setTimeout(function, 1000) is set to 1000 miliseconds so you can see the seconds ticking away.
<!DOCTYPE html>
<html>
<body>
<h1 id="clock"></h1>
<script>
window.onload = starttime;
function starttime()
{
var present = new Date();
var hour = present.getHours();
var minute = present.getMinutes();
var seconds = present.getSeconds();
if (minute < 10) minute = "0" + minute;
if (seconds < 10) seconds = "0" + seconds;
document.getElementById("clock").innerHTML
= "It is now " + hour + ":" + minute + ":" + seconds;
setTimeout('starttime()', 1000);
}
</script>
</body>
</html>
The next example shows how to put a clock on your screen. The setTimeout(function, 1000) is set to 1000 miliseconds so you can see the seconds ticking away.
<!DOCTYPE html>
<html>
<body>
<h1 id="clock"></h1>
<script>
window.onload = starttime;
function starttime()
{
var present = new Date();
var hour = present.getHours();
var minute = present.getMinutes();
var seconds = present.getSeconds();
if (minute < 10) minute = "0" + minute;
if (seconds < 10) seconds = "0" + seconds;
document.getElementById("clock").innerHTML
= "It is now " + hour + ":" + minute + ":" + seconds;
setTimeout('starttime()', 1000);
}
</script>
</body>
</html>
Set a date to midnight
To set a date to midnight use the setHours() function in the following way.
var testdate;
testdate = new Date();
testdate.setHours(0,0,0,0);
alert(testdate);
With setHours() we set the time to 0 hours, 0 minutes, 0 seconds and 0 milliseconds
To set a date to midnight use the setHours() function in the following way.
var testdate;
testdate = new Date();
testdate.setHours(0,0,0,0);
alert(testdate);
With setHours() we set the time to 0 hours, 0 minutes, 0 seconds and 0 milliseconds
Show minutes with two figures
The minutes in a date start with numbers containg just 1 figure (1, 2, 3 etc) If you need them to contain 2 figures you can add a leading 0 with padStart()
mins = String(new Date().getMinutes()).padStart(2, "0");
alert (mins)
The minutes in a date start with numbers containg just 1 figure (1, 2, 3 etc) If you need them to contain 2 figures you can add a leading 0 with padStart()
mins = String(new Date().getMinutes()).padStart(2, "0");
alert (mins)
Test if a date preceeds another date
Using greater then (<) or smaller as (<) we can test if a date preceeds another date. The next snippet shows how to do that.
var date1 = new Date(2021, 7, 31);
var date2 = new Date(2021, 8, 1);
if (date1 < date2)
{
alert ("date1 comes before date2");
}
Remember that months start counting at 0. Month 7 is therefore august.
Using greater then (<) or smaller as (<) we can test if a date preceeds another date. The next snippet shows how to do that.
var date1 = new Date(2021, 7, 31);
var date2 = new Date(2021, 8, 1);
if (date1 < date2)
{
alert ("date1 comes before date2");
}
Remember that months start counting at 0. Month 7 is therefore august.
Test if a date is between two other dates
This snippet takes the previous one a step further. With this snippet we test if a day falls between two other dates. This can be used for example to test wether a hotel room is free in a certain week.
var date1 = new Date(2021, 6, 10);
var date2 = new Date(2021, 6, 20);
var wanted = new Date(2021, 6, 15);
if ((wanted > date1) && (wanted < date2))
{
alert ("The room is free");
}
This snippet takes the previous one a step further. With this snippet we test if a day falls between two other dates. This can be used for example to test wether a hotel room is free in a certain week.
var date1 = new Date(2021, 6, 10);
var date2 = new Date(2021, 6, 20);
var wanted = new Date(2021, 6, 15);
if ((wanted > date1) && (wanted < date2))
{
alert ("The room is free");
}
What day is it in x days
Say there is an event in 15 days and you would like to know which day of the week that is. The next snippet shows how to get that information.
var futuredays = 8;
function naamvddag(futuredays)
{
const names=["sunday", "monday", "tuesday", "wednesday", "thursday", "friday","saturday","sunday"];
const today = new Date().getDay();
const future = futuredays % 7;
return names[((today + future) % 7)];
};
alert(naamvddag(futuredays));
We start with defining the variable futuredays and put the number of days in the future in. Next the array names gets all the names of the weekdays. The variable today gets the number of todays date. Because a week has seven days we use the remains of the calculation of the number of days /7 to get to the right array element.
Say there is an event in 15 days and you would like to know which day of the week that is. The next snippet shows how to get that information.
var futuredays = 8;
function naamvddag(futuredays)
{
const names=["sunday", "monday", "tuesday", "wednesday", "thursday", "friday","saturday","sunday"];
const today = new Date().getDay();
const future = futuredays % 7;
return names[((today + future) % 7)];
};
alert(naamvddag(futuredays));
We start with defining the variable futuredays and put the number of days in the future in. Next the array names gets all the names of the weekdays. The variable today gets the number of todays date. Because a week has seven days we use the remains of the calculation of the number of days /7 to get to the right array element.
What day is it today
new Date gives us all information about today. The first three letters give us the day of the week: mon, tue, wed,thu,fri,sat,sun We can use slice to get the day of the week.
var today = new Date();
today = today.toString();
alert (today)
var dayofweekweek = today.slice(0,3);
alert("Today is " + dayofweek);
new Date gives us all information about today. The first three letters give us the day of the week: mon, tue, wed,thu,fri,sat,sun We can use slice to get the day of the week.
var today = new Date();
today = today.toString();
alert (today)
var dayofweekweek = today.slice(0,3);
alert("Today is " + dayofweek);
What day is it today 2
To get the full name of the day you can use the next snippet:
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var today = new Date();
var dayname = days[today.getDay()];
alert(dayname)
Change New Date() into any date you like or leave it empty for the current day.
To get the full name of the day you can use the next snippet:
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var today = new Date();
var dayname = days[today.getDay()];
alert(dayname)
Change New Date() into any date you like or leave it empty for the current day.
What is todays date
The next snippet shows how to get todays date in the month-day-year format.
var current = new Date();
var day = String(current.getDate()).padStart(2, '0');
var month = String(current.getMonth() + 1).padStart(2, '0');
var year = current.getFullYear();
current = month + "-" + day + "-" + year;
alert(current);
The next snippet shows how to get todays date in the month-day-year format.
var current = new Date();
var day = String(current.getDate()).padStart(2, '0');
var month = String(current.getMonth() + 1).padStart(2, '0');
var year = current.getFullYear();
current = month + "-" + day + "-" + year;
alert(current);
Which date of two dates is the most recent.
To check which date of two dates is the most recent we just have to compare the two dates.
var date1;
var date2;
date1 = new Date( "Aug 31, 2020" );
date2 = new Date( "Dec 10, 2019" );
if (date1 > date2)
{
alert("The first date is the most recent");
}
else
{
alert("The second date is the most recent.");
}
To check which date of two dates is the most recent we just have to compare the two dates.
var date1;
var date2;
date1 = new Date( "Aug 31, 2020" );
date2 = new Date( "Dec 10, 2019" );
if (date1 > date2)
{
alert("The first date is the most recent");
}
else
{
alert("The second date is the most recent.");
}
Which day in the year is it
If we need to know which day it is (aka how many days have past since january 1) we can use the next snippet.
milisecs = (new Date() - new Date(new Date().getFullYear(), 0, 0))
days = milisecs / 1000 / 60 / 60 / 24
alert (parseInt(days))
The first step is to subtract the first day of the year (new Date(new Date().getFullYear(), 0, 0) from the currect day (new Date()). That gives us the total number of milliseconds and we then just have to divide that by the number of milliseconds in a day.
If we need to know which day it is (aka how many days have past since january 1) we can use the next snippet.
milisecs = (new Date() - new Date(new Date().getFullYear(), 0, 0))
days = milisecs / 1000 / 60 / 60 / 24
alert (parseInt(days))
The first step is to subtract the first day of the year (new Date(new Date().getFullYear(), 0, 0) from the currect day (new Date()). That gives us the total number of milliseconds and we then just have to divide that by the number of milliseconds in a day.
Which of the x days is the most recent
The next snippet shows how to get the most recent date from an array with dates.
var dates = [
new Date(2021, 5, 12),
new Date(2020, 7, 10),
new Date(2021, 9, 9)
];
function mostrecent(...dates)
{
fulldate = new Date(Math.max(...dates));
recent = fulldate.getFullYear()+" : "+fulldate.getMonth()+" : "+fulldate.getDate()
return recent
}
alert(mostrecent(...dates));
The next snippet shows how to get the most recent date from an array with dates.
var dates = [
new Date(2021, 5, 12),
new Date(2020, 7, 10),
new Date(2021, 9, 9)
];
function mostrecent(...dates)
{
fulldate = new Date(Math.max(...dates));
recent = fulldate.getFullYear()+" : "+fulldate.getMonth()+" : "+fulldate.getDate()
return recent
}
alert(mostrecent(...dates));
Which year is it
A simple snippet to determine which year it is.
var datenow = new Date();
var currentyear = datenow.getFullYear();
alert(currentyear);
A simple snippet to determine which year it is.
var datenow = new Date();
var currentyear = datenow.getFullYear();
alert(currentyear);