Working With Time is very common in all programming languages.
In this tutorial I want to take you through the basics of dealing with dates and times in JavaScript and some code snippets that I commonly use in my flows.
The key to working with time in JavaScript is the Date object.
So the first thing you need to do is to get a date object. There are several ways of doing this but the most basic is:
var d=new Date();
This creates a date object with the current date and time if you print it it looks like this.
2020-06-08T16:14:36.457Z
However this is not the only way you can create a new Date object there are several other methods which you might find useful:
- new Date()
- new Date(year, month, day, hours, minutes, seconds, milliseconds)
- new Date(milliseconds)
- new Date(date string)
Example:. Creating a Object Using a Date String
var date = new Date('September 22, 2018 13:22:13')
JavaScript Time Stamp and Unix Time stamp
JavaScript stores time in milliseconds since Jan 1st 1970 (UTC) (Unix Time).
However if you have data with a Unix time stamp then this will be seconds and not milliseconds.
So to convert a Unix time stamp into a JavaScript time stamp you need to multiple by 1000.
When working with time the most common thing to do is to get a Unix type time stamp using the getTime method as shown in the screen shot below:
If you have an existing Unix type time stamp then you can also use this time stamp to create the date object from that time stamp.:
var d=new Date(timestamp);
This is common when you are ready to display data and need to convert the time stamp into a more user friendly form.
Generally we use times in Unix time stamp format which makes them very easy to work with , and convert them into a human readable format to display them.
Examples:
1.Calculating interval between events
var d=new Date(); var start_time=d.getTime() //something happens here d=new Date(); var end_time=d.getTime() var difference =end_time-start_time;
2. Comparing Times
var d=new Date(); var time1=d.getTime() d=new Date(); time2=d.getTime() if(time1<=time2) //do something
Converting Dates for Display
The following table shows the common Date display forms
JavaScript Date Formats | |
ISO Date | “2015-03-25” =year-month-day (The International Standard) |
Short Date | “03/25/2015” =month/day/year |
Long Date | “Mar 25 2015” or “25 Mar 2015” |
You can extract the current day, month,year and seconds etc from the Date object using the get methods which all return local time:
var d=new Date(); var day=d.getDate() //day as a number 1 -31 var weekday=d.getDay() //-weekday as a number 0-6 var month=d.getMonth() // month as a number 0-11 var year=d.getFullYear() //year as a four digit number (yyyy) var hours=d.getHours() //the hour (0-23) var minutes=d.getMinutes() //-the minute (0-59) var seconds=d.getSeconds() //-the seconds (0-59)
However there is also a UTC equivalent of each that returns the time in UTC e.g
var hours=d.getUTCHours() //the hour (0-23)
The screen shot below show it’s use:
To get the month by name use:
var months={1:"January",2:"February",3:"March",4:"April",5:"May",6:"June",7:"July",8:"August",9:"September",10:"October",11:"November",12:"December"}; var month=d.getMonth(); var month_name=months[month];
You can do a similar thing for weekdays
Formatting Time for Display
When displaying dates and time on graphs,tables etc we usually want it to be in human readable form.
In addition we usually want the display a month as 01 for Janauary and not just 1. The same also applies for days
Example 1- Create date of form day/month/year e.g.09/04/2020.
This example uses the get methods
var d=new Date(); var day=d.getDate(); var month=d.getMonth(); var year=d.getFullYear(); if(day<=9) day="0"+day; if(month<=9) month="0"+month+1; var date_out= day+"/"+month+"/"+year;
Example 2- Create date of form Day/Month/Year e.g. 09/04/2020.
In this example we use the tostring() methods:
toLocaleString() and toLocaleTimeString() as shown below:
Converting Formatted Time Back to a Unix Timestamp
Sometimes you will you have data were the date and time is already formatted and you need to convert it back into a Unix type timestamp.
Here we use this from of the new date constructor
new Date(year, month, day, hours, minutes, seconds, milliseconds)
So if our date looks like this:
2020-08-8,14:30:00
Then we can use the following code to get a Unix Type time stamp:
var Data="2020-08-8,14:30:00"; var data=Data.split(","); var time=data[1]; data=data[0].split("-"); var year=data[0]; var month=data[1]-1; //notice the -1 var day=data[2] time=time.split(":"); var hours=time[0]; var mins=time[1]; var secs=time[2]; var d= new Date(year,month,day,hours,mins,secs); msg.payload=d msg.timestamp=d.getTime(); return msg;
If I paste the code into a function node and use the debug node to view the output this is what we see.
You should also notice that one displays the local time and the other displays the time in GMT (UTC).
Changing a Date
The data object has both get methods and set methods.
So if we wanted to change the hours we use:
date.setHours(newValue)
Example: Add 1 hour to current time
var date=new Date(); var hour =date.getHours(); hour=hour+1; date.setHours(hour);
Note: in the above we would also need to check that we didn’t go past midnight in which case we would go on to the next day and would need code to take that into account.
Example: Add 1 hour to current time
var date=new Date(); var timestamp =date.getTime(); timestamp=timestamp+(3600*1000); //1hour in milliseconds
Note: Now we don’t need to worry about the overflow into a new day which is why I find it easier to use a time stamp internally in my flows.
Timezones
Universal Time (UTC) and Greenwich Mean Time (GMT) are the same thing, and time is store in the Date object in UTC.
When creating a date object the local time is assumed but you can pass in a Timezone offset to store the local time of another location in the date object.
There are two formats to use, You can use the time offset from GMT or the time zone abbreviation (PDT =Paciffic daylight time):
new Date('September 26, 2018 19:20:00 PDT') new Date('September 26, 2020 19:20:00 -0700')
A useful function for working with time zones is the getTimezoneOffset() which returns the minutes. Note in the screenshot below the local time is British summer time which is UTC+1 the offset returned is -60.
If we had TTC+5 then -300 would be returned.
A list of offsets and abbreviations is here
Summary
JavaScript as a whole collection of functions for working with time. Generally you store time a Unix type time stamp in Milliseconds and only convert it when it is displayed.
Likewise if you are working with different time zones then use Unix type time stamp internally and convert it for display.
Related Tutorials and Resources:
- W3 schools tutorial
- Definitive Guide to JavaScript Dates
- Understanding dates and times
- Using the Node-Red Function Node- Beginners Guide
- Working with Node-Red variables
Steve,
I see that my ui table shows info where the entries are one day before the database date. Yet my database shows the correct date. Seems very odd indeed. Not sure on how to sort that one.
Nick
I can only think that there is something wrong with the update or are you retrieving the data from the database to display in the table-ui?
Rgds
Steve
Steve,
I am gathering the data from the database and displaying it on a ui table.
Cheers,
Nick
Nick
then it is probably the query if the flow isn’t too big and confidential then you can send it to me and I’ll take a quick look.
Use the ask Steve page so we can do it via email.
Rgds
Steve
Hi Steve,
Having trouble with my email at the moment. I will paste in the sql query that I use under here.
The database table = datab
The date is called, now
SELECT now, sensor1, sensor2 from datab
group by sensor1, datab;
Sending that sql query manually works. But when I package it up for node red like this:
msg.topic = “SELECT now, sensor1, sensor2 from datab, group by sensor1, datab”;
return msg;
I then get an error. The date is now ok. I must have a glaring error there in my way of packaging it up and not getting the list back that shows up fine when I enter a manual sql query.
Thanks, Nick
Nick the database query looks wrong.
The lines below are from my website monitor which logs page load times and lets you query based on start date and end date.
The timestamp fields in the database contains the time.
Because the query is long it is split into parts.
var part_msg=” AND TIMESTAMP >”+sdate+ ” AND TIMESTAMP<"+edate+ " "; query ="SELECT * FROM SITES WHERE SITE="+"\""+data.site+"\""+part_msg+" ORDER BY TIMESTAMP DESC LIMIT 100"; If that doesn't help you are welcome to have a copy of the flow to work from just contact me via the ask steve page and I will email it to you. Rgds Steve
Steve,
Node red needed a restart and now the query functions. I never saw this happen before. I will ensure to periodically restart node red in the future when things that work manually, decide not to work when put into a msg.
Thanks for your input.
Nick
Hi Steve,
I have a start date and an end date. I need the difference of these dates. For example in minutes.
Formate is like this:
start: “2024-04-12T13:48:32Z”
end: “2024-04-12T13:57:14Z”
What would be the easiest way to manage this?
Thanks in advance and best regards,
Kerem
> d= new Date(“2024-04-12T13:48:32Z”)
2024-04-12T13:48:32.000Z
> s=d.getTime()
1712929712000
> d= new date(“2024-04-12T13:57:14Z”)
Uncaught ReferenceError: date is not defined
> d= new Date(“2024-04-12T13:57:14Z”)
2024-04-12T13:57:14.000Z
> e=d.getTime()
1712930234000
> e-s
522000
you need to put the code in a function node
rgds
steve
Thanks Steve for those details.
Is it possible to actually set the date time on my raspberry-pi (or any MCU board) from inside node-red?
I would try using the exec node and the linux date command
https://www.cyberciti.biz/faq/howto-set-date-time-from-linux-command-prompt/
rgds
steve
Hello,
thaks
how i get this format?
2023-10-25T10:00:00+01:00
thanks
Hi
try
let d=new Date();
let s= d.toString();
Take a look here
https://flaviocopes.com/javascript-dates/
Rgds
Steve
//—-
var d=new Date();
var day=d.getDate() //day as a number 0 -31
//—
isn’t it 1-31?
Yes you are correct sorry about that
Rgds
Steve
Hi Steve,
Thank you for your post.
How to code in order to have this format:
ts : “2022-07-05T08:28:55.043461”
It looks like what you get with the new date function
d=new Date()
2022-07-06T12:52:33.993Z
Oh, Thank you very much. I’m sorry, I’m late.
I used Date/Time Formatter node.
Why I dont get that, I get something like “27th of jan 2022″ or 01/27/2022, 8:34:00 PM”
Sorry
What do you think you should be getting?
Rgds
Steve
But as a noob, I get all the convigurations, but I don’t see how to display it on a dashboard…..
Assume you mean display time. You can use a simple test node as it is a text string or a template node. Does that help or do you want an example flow.
Rgds
Steve
Steve,
The: Example 1- Create date of form day/month/year e.g.09/04/2020.
is missing month +1. Month is returned 0-11, not 1-12.
Good write up overall, well done.
Ashex
Tks for pointing that out I will correct it.
Rgds
Steve