Shaker Cabinets With Slab Drawers

Very often in programs you have to work with a date or times. For this JavaScript offers us the date object. This has a few special features, which are shown in the following tutorial. For testing in the first part the console of the browser is clever again. Here we can directly enter JavaScript commands and see the result. So let’s type in the console


It is important that the JavaScript command Date() is written in capital letters! As a result we get a long return of the current time. In the following just as an example: Tue Jan 08 2019 13:39:52 GMT+0100 (Central European Standard Time) What did we get back? If we split it at each space, it becomes clearer:

Tue Day in English 3-letter notation, so Tuesday in the example.
Jan Month in English 3-letter notation, so January
08 day with leading zero
13.39:52 the time with hours:minutes:seconds
GMT Which time zone, here “Greenwich Mean Time”.
0100 The time difference – in Germany is in the winter half year 1 hour later than the coordinated world time (abbreviation UTC, so that one has seen this). (Central European Standard Time)

We get exactly the date and time at the time we execute this command. Often this value is assigned to a variable – but then the value is fixed and the time and date remains “standing”. There are other ways to create a new date object. As an overview all 4 variants and then the following explanations:

new Date() new Date(year, month, day, hour, minute, second, millisecond) new Date(millisecond) new Date(date string) 

If we want to specify a date ourselves, the first variant does not really help us. In the second variant we can specify a date ourselves. There are a few pitfalls here! Let’s take a closer look at the structure:

new Date(year, month, day, hour, minute, second, millisecond) 

We don’t have to enter all values. We just enter the first value – the year 2019.

new Date(2019) 

If we now simply enter the year in the console, i.e. the first value, we get the following result in the output: Thu Jan 01 1970 01:00:02 GMT+0100 (Central European Standard Time) What happened? We have accidentally entered the third form of the input, i.e. we have entered milliseconds, which we thought to be the year. A date needs at least the year and the month. Since all computers start counting at 1.1.1970 at 0 o’clock, 2019 milliseconds are added to 1.1.1970 to our previous specification. This is how the output value comes about. The 1 o’clock comes about because we work with the Central European Standard Time, i.e. 1 hour is added to the time. IMPORTANT therefore with the use of the input of Date(Year, Month, Day) is, that we add at least the month next to the year. And there we come to the next pitfall. We now want to enter the first April. Let’s make the following entry in the console:

Date(2019, 4) 

We get as result: Wed May 01 2019 00:00:00 GMT+0200 (Central European Summer Time) April, April – the computer takes us for a ride and displays May. Why? Actually, one would assume with common sense that JavaScript starts counting the months with 1. So January would be 1 – but this is not the case. JavaScript starts counting with 0! Our January is 0 in JavaScript, February is 1, our April is 3 and so on. So if we want our April 1, please specify the following.

Date(2019, 3) 

If we pass the year with 2 digits it will be interpreted as 19xx!

Date(18, 3) 

Our input thus results in 1918: Mon Apr 01 1918 00:00:00 GMT+0100 (Central European Summer Time) {} That’s it for now with the nastiness and stumbling blocks. Now we can add day, hour, minute, second and even the millisecond. Can – but don’t have to. Just try it once.

new Date(millisecond) – Input over milliseconds

Here the milliseconds are calculated since January 1st 1970. This date is based on the appearance of the operating system Unix and is strictly speaking arbitrary. One needed a starting point to calculate – so why not the 1.1.1970? If you enter the following in the console, you get this “birthday”:

new Date(0); 

Of course the whole thing is a bit clumsy to calculate something with it yourself. One day, 24 hours, consists of 86.400.000 milliseconds. But the real use is rather in comparison. You can store the time in a variable when a program is started and then the time when it is finished and subtract these two times from each other and get the program runtime in milliseconds. So there are quite clever application possibilities. If you want to get a date before 1/1/1970, then you specify negative numbers.

Available methods for Date()

Usually one does not want monstrosities as output like “Mon Apr 01 1918 00:00:00 GMT+0100”. Therefore you can use methods to get exactly the information you need from the date and work with it.

Method Explanation
getFullYear() Year as 4-digit number (YYYY)
getMonth() Month as number, starting with 0! (0-11)
getDate() day as number (1-31)
getHours() hour (0-23)
getMinutes() minute (0-59)
getSeconds() second (0-59)
getMilliseconds() millisecond (0-999)
getTime() Past milliseconds since 1/1/1970
getDay() Weekday as number (0-6) current date (as of ECMAScript 5)

    • Share WhatsApp
    • tweet
    • Share Facebook
    • pin it
    • Share
    • share
    • share
    • share

Since JavaScript’s date functions are very extensive, it’s worth taking a closer look here. In the following we want to show you some examples how to deal with JavaScript and data in a meaningful way.

The Date object in general

If you want to work with date or time, the Date object is inevitably a companion. It provides access to methods that are useful for specifying and processing time and date or time intervals.

Creating a Date object

A new Date object is created with the call new Date(). This should be passed to a variable for processing. Example: a = new Date(); In addition, passing parameters is possible. The following can be used:

  • Milliseconds – Specifying milliseconds will create a Date object with the date having the number of milliseconds from Jan 01, 1970 00:00:00. For example, one second later would be the value 1000 and 1 year later, the value would be 1000*60*24*365 (millisecond*second*minute*day*year).
  • String – By specifying a string as a parameter, a Date object is created that contains the values extracted from the string. For this, it is necessary that the string is passed in the correct format. As an example: ‘Mon Jun 18 15:11:39 UTC+0200 2001’ means: Monday the 18.07.2001 15 o’clock 11 minutes 39 seconds +2 hours after UTC (~ time zone).
  • Year, Month, Date [+ x] – Specifying the three parameters Year, Month, Date will create a Date object with the defined year, month and date and the time 00:00:00. Optionally, this chain can be extended by the values hours, minutes, seconds and milliseconds (in this order). It is to be noted in each case that January has the value 0 (zero), February the value 1 (etc.).

Example: a = new Date((1000*60*24*365*30)+(1000*60*24*7)); //30 years + 7 days (leap years) = Sat Jan 1 01:00:00 UTC+0100 2000 b = new Date(‘Jul 15 01:30: 00 2001’); // = Sun Jul 15 01:30:00 UTC+0200 2001 c = new Date(2001, 11, 24); // = Mon Dec 24 00:00:00 UTC+0100 2001 d = new Date(2001, 11, 24, 18, 19); // = Mon Dec 24 18:19:00 UTC+0100 2001

Local time

The word local time does not mean a period of time that is particularly suitable for going to the next bar/restaurant. By local time, in the context of the Date object, we mean the time that is set on the computer on which the script is executed. In particular, the time difference plays a more important role. Most methods calculate according to local time, the methods that do not calculate according to local time are marked with UTC in their names.

Displaying the time

For all gimmicks with date and time the date object is always necessary – so also, if the current time is to be indicated. The date object has its own method for the output of the individual values such as hours, minutes or seconds, which we can use here. Das folgende Skript schreibt die aktuelle Uhrzeit in die Variable zeit: a = new Date(); b = a.getHours(); c = a.getMinutes(); d = a.getSeconds(); zeit = b+’:’+c+’:’+d; Haben wir die Zeit erstmal, kann sie überall hin ausgegeben werden, zum Beispiel in der Statusleiste: Uhrzeit … Mit dem onload-Ereignis wird hierbei ein Intervall erzeugt, dass jede Sekunde die Funktion ausgabe erneut aufruft und damit das Erneuern der Uhrzeit vorantreibt.

Verweildauer anzeigen

Das obige Beispiel zeigt lediglich die aktuelle Zeit an. Was aber, wenn die Verweildauer auf einer Seite angezeigt werden soll? Auch hierfür wird das date-Objekt benötigt – und zwar gleich zweimal. Das System ist folgendes: Betritt der Besucher eine Seite, wird die Zeit des Eintritts gespeichert. Innerhalb eines Intervalls wird dann die aktuelle Zeit mit der Eintrittszeit verglichen und die Differenz errechnet. The calculated result can finally be output. To store the entry time it is sufficient to create a date variable when loading the page: var entry = new Date(); The difference can be calculated as follows: function duration() { now = new Date(); b = new Date(now-entry); c = (b. getHours()-1)+”; if(c.length == 1){c = ‘0’+c;} d = (b.getMinutes())+”; if(d.length == 1){d = ‘0’+d;} e = (b.getSeconds())+”; if(e.length == 1){e = ‘0’+e;} time = c+’:’+d+’:’+e; window.status = time; } Now all that’s missing is an interval to call the display all the time:

Calculate age

An often very interesting application is the calculation of the exact age (including months, days, hours and minutes). The calculation is done, as in the example above, by comparing two dates: The date of birth and the current date and time. So, as a first requirement, we need an input option for the date of birth. We take for this a form with the following input fields: Year, Month, Day, Hours, Minutes as well as an OK button. The form results like this:

Day.Month.Year: . .
Hours.Minutes: :

Please make sure that the form, as well as all fields, are uniquely named to ensure error-free access. The following script creates a date from the given data: function calculate() { a = parseInt(document.form1.year.value); b = parseInt((document.form1.month.value)-1); c = parseInt(; d = parseInt(document. form1.hours.value); e = parseInt(document.form1.minutes.value); f = new Date(a,b,c,d,e); g = new Date(); minutes = g.getMinutes()-f.getMinutes(); hours = g.getHours()-f.getHours(); days = g.getDate()-f.getDate(); months = g. getMonth()-f.getMonth(); years = g.getYear()-f. getYear(); if(minutes<0){minutes = 60+minutes; hours--;} if(hours<0){hours = 24+hours; days--;} if(days<0){days = 30+days; months--;} if(months<0){months = 12+months; years--; } if(years>2000){years = years-2000} if(years>1900){years = years-1900} alert(‘You are n’+ ‘- ‘+years+’ years and n’+ ‘- ‘+months+’ months and n’+ ‘- ‘+days+’ days and n’+ ‘- ‘+hours+’ hours and n’+ ‘- ‘+minutes+’ minutes old. ‘); } The whole thing then goes into the head section of the page. However, you should note that the above script is not 100% correct: A month is counted with 30 days – so some days may be missing. Also leap years are not included.

Timeouts and intervals

Intervals and timeouts are very useful for things that should run one after the other. An interval is a recurring event in equal time intervals. A timeout is a part of an interval – the event occurs only once after it was started, then not again. For both, the window object provides the corresponding functions: setTimeout to create a timeout and setInterval (with an “L”) to create an interval. Beide Funktionen erwarten als ersten Parameter einen String der einen Funktionsaufruf beschreibt, also z.B. ‘machwas(1,2,3)’. Als zweiter Parameter wird jeweils die Anzahl der Millisekunden erwartet nach denen das Ereignis eintreten soll: 1000 Millisekunden sind eine Sekunde, 60000 Millisekunden sind eine Minute usw. Ein Beispiel: Timout
Intervall starten
Intervall beenden
Im Beispiel sind drei Funktionen definiert, die jeweils mit einem Link verknüpft sind. Die Funktion sTime startet ein Timeout, der nach einer Sekunde abläuft. Entsprechend wird also nach einer Sekunde die Nachricht ‘1 Sek. vorbei’ angezeigt. Die Funktion sInt startet ein Intervall, das im Abstand von 10 Sekunden auftritt und die Meldung ’10 Sek. vorbei’ anzeigt. Since this is a recurring event, it must be possible to cancel it somehow. To do this, the method outputs a code (usually a unique number) that defines the interval. The third function, bInt, terminates the interval by the clearInterval method of the window object. It is passed the value previously output by the setInterval.

About us

Tutorial by Stefan Trost | Last update on 22.11.2022 | Created on 04.10.2015 Today I want to show you how to use JavaScript to get the current date and time and use them in your script. We need JavaScript’s Date object for both, which we can create as follows:

var today = new Date(); 

After that we can read all needed values to get the current date as well as the current time and process them in our script.

Get the current date

First, let’s look at how we can get the current date (we’ll get to the time in the next section). First we create our Date object and then we read out the year, the month and the day.

var today = new Date(); var d = today.getDate(); var m = today.getMonth() + 1; var y = today.getFullYear(); var dmy = d + "." + m + "." + y; alert(dmy);

To get the tag we use the method .getDate(). This provides us with the day of the month as a number from 1 to 31. To get the month we then use the .getMonth() method. This time we still have to add 1 to the value we get, because JavaScript gives us the month as a number between 0 and 11. This is not necessary with .getDate(). Here, the value 0 corresponds to January, the number 11 to December, and so on. Finally we use .getFullYear() to also get the year for our date. It is called .getFullYear() because the method is distinct from the related .getYear() method. With .getFullYear(), we get the year as a 4-digit number while .getYear() returns a 2-digit number for years between 1900 and 1999. From 2000 onwards .getYear() will return 3 digits starting at 100, before 1900 .getYear() will return negative values. Due to this issue (cue year 2000 problem) .getYear() has since been removed from the web standard and should no longer be used. For this reason, we should always fall back to .getFullYear(), as .getYear() may eventually no longer be supported by browsers. After getting the current day, current date, and current year, we combine the individual components into a date in the format day.month.year and output it via alert(). Of course, this example is just to demonstrate the function, in practice we can of course combine the values as we wish or use them in other ways.

Get current time

The current time can also be found out via the Date object. How to do this is shown in the next example.

var today = new Date(); var h = today.getHours(); var m = today.getMinutes(); var s = today.getSeconds(); var t = h + ":" + m + ":" + s; alert(t);

Analogous to the methods to get the components of the date, this time we use the .getHours(), .getMinutes() and .getSeconds() methods to get the current hour, minute and second respectively. We get values from 0 to 59 and 0 to 23 respectively. Furthermore, the Date object also provides us with the .getMilliseconds() method in case we also want to get the milliseconds are needed. In our example, we use the read values again to display the current time via an alert() message. A date can be read in JavaScript using the object Date object. To access the components of a date, there are some functions, which we will introduce below. Furthermore, there are also functions that allow to modify the date afterwards. To initialize (i.e. create) a date, we present 4 different variants. For all variants it is necessary to create a Date-object by means of the constructor. As a reminder: For this we note the keyword new followed by the object name (i.e. Date) and a pair of parentheses. Inside the brackets we pass the function parameters (constructed parameters). In the first variant, we do not pass any parameter to the function. Thus the created date gets the current date with current time.

var date = new Date();

The second option is to pass a numeric value to the function. This numeric value must contain the so-called UNIX timestamp as a millisecond value as a millisecond value. The UNIX timestamp is a numeric value that represents the seconds since 01/01/1970 at midnight until the desired time.

var date = new Date(1451602800000); // Corresponds to 01/01/2016 00:00:00

Another variant is to give the constructor the parts of the date and time to the constructor. The order year, month, day, hour, minute, second, millisecond must be followed. Please note that the month specification is zero-based, i.e. month 0 corresponds to January (1), month 1 corresponds to February (2), … and month 11 corresponds to December (12).

var date = new Date(2016, 1, 1, 3, 4, 5, 678); // Corresponds to 2016-02-01 03:04:05,678

The last variant is to specify a string. Here the date (possibly with time) must be passed in a specific format. Unfortunately, there may be problems here with some browsers, since not all formats are supported by every browser. The use of the ISO-8601 format is considered safe and should be supported by all browsers.

var date = new Date("2016-02-01"); // Corresponds to 01.02.2016 00:00:00


Read date parts

As already mentioned above, there are some functions to read out the components of a date and time. There are functions with which the UTC date or time can be read. UTC time and the local date resp. local time can be output. If a millisecond value is passed in the constructor, the time difference for the local time is also included. When specifying the individual date and time components, exactly the noted specification is interpreted as local time. If the string is specified, it will be interpreted as UTC time unless otherwise explicitly specified in the string.

Local time getDay() Returns the day of the week (0 = Sunday, 1 = Monday, …, 6 = Saturday).
getDate() Returns the day of the month (1 – 31).
getMonth() Returns the month (0 = January, 1 = February, …, 11 = December).
getFullYear() Returns the year.
getHours() Returns the hours (0 – 23).
getMinutes() Returns the minutes (0 – 59).
getSeconds() Gibt die Sekunden zurück (0 – 59).
getMilliseconds() Gibt die Millisekunden zurück (0 – 999).
UTC-Zeit getUTCDay() Gibt den Wochentag zurück (0 = Sonntag, 1 = Montag, …, 6 = Samstag).
getUTCDate() Gibt den Tag des Monats zurück (1 – 31).
getUTCMonth() Gibt den Monat zurück (0 = Januar, 1 = Februar, …, 11 = Dezember).
getUTCFullYear() Gibt das Jahr zurück.
getUTCHours() Gibt die Stunden zurück (0 – 23).
getUTCMinutes() Gibt die Minuten zurück (0 – 59).
getUTCSeconds() Gibt die Sekunden zurück (0 – 59).
getUTCMilliseconds() Gibt die Millisekunden zurück (0 – 999).

Hier folgendes Beispiel zur Ausgabe einiger Datumsbestandteile:

var datum = new Date(); document.write("Datum: " + datum.getDate() + "
"); document.write("Monat: " + (datum.getMonth() + 1) + "
"); document.write("Jahr: " + datum.getFullYear() + "


Datumsteile ändern

Passend zu den Funktionen zum Auslesen der Datumsbestandteile gibt es auch Funktionen zum Setzen der Datumsbestandteile. Again, there are functions for UTC time and local time.

Local time setDate() Sets the day of the month (1 – 31).
setMonth() Sets the month (0 = January, 1 = February, …, 11 = December).
setFullYear() Sets the year.
setHours() Sets the hours (0 – 23).
setMinutes() Sets the minutes (0 – 59).
setSeconds() Sets the seconds (0 – 59).
setMilliseconds() Sets the milliseconds (0 – 999).
UTC time setUTCDate() Sets the day of the month (1 – 31).
setUTCMonth() Sets the month (0 = January, 1 = February, …, 11 = December).
setUTCFullYear() Sets the year.
setUTCHours() Sets the hours (0 – 23).
setUTCMinutes() Sets the minutes (0 – 59).
setUTCSeconds() Sets the seconds (0 – 59).
setUTCMilliseconds() Sets the milliseconds (0 – 999).
var datum = new Date(); datum.setDate(29); datum.setMonth(0); document.write("Datum: " + datum.getDate() + "
"); document.write("Monat: " + (datum.getMonth() + 1) + "
"); document.write("Year: " + date.getFullYear() + "

  By the way: With the help of the function getTimezoneOffset() it is possible to get the time difference between UTC time and local time. The function returns a minute value. In Germany the function returns -60 (for winter time) or -120 (for daylight saving time).

Formatted output

There are some predefined functionsto output the date and time. All functions except toUTCString() and toISOString() return the local time. The following table shows all available functions for formatted output:

toLocaleDateString() Returns the date (local representation).
toDateString() Returns the date.
toLocaleTimeString() Returns the time (local representation).
toTimeString() Returns the time.
toLocaleString() Returns the date and time (local representation).
toString() Returns the date and time.
toUTCString() Returns the date and time with UTC time.
toISOString() Returns the date and time in ISO format.

Again and again it can happen that you format the format the date and time differently. want to do. However, we have to write such a formatting function ourselves. So, in contrast to languages like C (function strftime()), it is not possible to call a function with so-called abbreviations. With the help of the functions getX() it is however possible to assemble our output. For this the following example:

var date = new Date(); document.write("Date: " + date.getDate() + "." + (date.getMonth() + 1) + "." + date.getFullYear()); document.write("
"); document.write("Time: " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds());

As you will surely notice, the above example does not have any leading zeros are visible. A function to pad numbers with leading zeros does not exist in JavaScript either, which means we have to write such a function ourselves as well. Since we have not yet discussed how to define our own functions, we have solved the “problem” with the leading zeros with one-line if-conditions directly in the output.

var date = new Date(); document.write("Date: " + (date.getDate() >= 10 ? date.getDate() : ("0" + datum.getDate())) + "." + ((date.getMonth() + 1) >= 10 ? (date.getMonth() + 1) : ("0" + (date.getMonth() + 1))) + "." + date.getFullYear()); document.write("
"); document.write("Time: " + (datum.getHours() >= 10 ? datum.getHours() : ("0" + datum.getHours())) + ":" + (datum.getMinutes() >= 10 ? datum.getMinutes() : ("0" + datum.getMinutes())) + ":" + (datum.getSeconds() >= 10 ? datum.getSeconds() : ("0" + datum.getSeconds())));

  Important: To understand the operation of the Date-object, it is recommended to try out the functions as well as inputs and outputs of the Date object with the help of smaller “test programs”. Shaker Cabinets With Slab Drawers.

Leave a comment

Your email address will not be published. Required fields are marked *