Creating an timestamp ?

I dont have code because I cant work out how to do this. The functional requirement though are these.

1.) Given a year, month, day, hour,minute and second I want to return a timestamp
2.) Given that timestamp I want to add 7 days to it and get the new timestamp.

Can anyone give me an example of how to do it. So in my use case I need to state when an event takes place for the first time. And each day check if the current day is an expected number of days since a specific date.

unix timestamps are convenient and can be created using the Arduino TimeLib.h library.

Some examples:

//unix timestamp examples

#include "TimeLib.h"

tmElements_t te;  //Time elements structure
time_t unixTime; // a time stamp

void setup() {
  Serial.begin(9600);
  // what is the current system time after startup?
  Serial.print("Startup: now() = "); //current time
  Serial.println((unsigned long) now());
  delay(3000);
  Serial.print("after 3s delay, now() = ");
  Serial.println((unsigned long) now());

  // display date_time in Arduino-speak
  Serial.print("day/date @startup+3s : ");
  Serial.print(day());
  Serial.print("/");
  Serial.print(month());
  Serial.print("/");
  Serial.print(year());
  Serial.print(" ");
  Serial.print(hour());
  Serial.print(":");
  Serial.print(minute());
  Serial.print(":");
  Serial.println(second());

  // new internal clock setting.
  // convert a date and time into unix time, offset 1970
  te.Second = 0;
  te.Hour = 23; //11 pm
  te.Minute = 0;
  te.Day = 1;
  te.Month = 1;
  te.Year = 2017 - 1970; //Y2K, in seconds = 946684800UL
  unixTime =  makeTime(te);
  Serial.print("Example 1/1/2017 23:00 unixTime = ");
  Serial.println(unixTime);
  setTime(unixTime); //set the current time to the above entered
  Serial.print("now() = ");
  Serial.println(now());
  // print as date_time
  print_date_time();
  // add
  unixTime += 7200UL; //add 2 hours
  setTime(unixTime);
  Serial.println("After adding 2 hours");
  Serial.print("now() = ");
  Serial.println(now());
  print_date_time();
}
void print_date_time() { //easy way to print date and time
  char buf[40];
  sprintf(buf, "%02d/%02d/%4d %02d:%02d:%02d", day(), month(), year(), hour(), minute(), second());
  Serial.println(buf);
}

void loop() {}

1 Like

Thank you, I will give it a go :smiley:

I'm using platform IO and searching the libraries, there are none for TimeLib.h, is there another name for it

Are you allowed to use existing libraries to achieve this? Or must you write your own code from scratch? I hope it is the former, because otherwise it can be quite tricky. Converting minutes, hours and days into a timestamp is easy because they are all the same length. But months are not, and years are not either, because of leap years. So not easy, but interesting, I suppose!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.