Jump to content

[TOPIC: topicViewTemplate]
[GLOBAL: userSmallPhoto]

Working with dates in Lua/Corona
Started by dalekirkwood May 27 2019 06:33 AM

2 replies to this topic
[TOPIC: post.html]


[GLOBAL: userInfoPane.html]
  • Observer

  • 7 posts
  • Corona SDK

Hi All


I am hoping you can help me answer this. I have some dates stored in a table. I store each part separately.

                myTable[i].dateday = datetime.day
		myTable[i].datemonth = datetime.month
		myTable[i].dateyear = datetime.year
		myTable[i].timehour = datetime.hour
		myTable[i].timemin = datetime.min
What I cannot seem to work out is how on earth I take a date and deduct a number from it.
So I want to see the records from the last 7 days.
I cant just take the system day and deduct 7 days, or can I?
From what I am reading, I have to create a time stamp and use that. This seems to me to be very long winded for something as simple as deducting days from a date.
I see from some other posts, I am not the only one who has struggled with this.
Thanks for the help.


[TOPIC: post.html]

Rob Miracle

[GLOBAL: userInfoPane.html]
Rob Miracle
  • Moderator

  • 26,072 posts
  • Enterprise

As answered in Slack: you will need to parse the date into its components and use the os.date() function to convert it to seconds since Jan 1, 1970 at midnight (Epoch or the standard Unix 0 date). Then subtract (7 * 86400) (seconds in a day), then use os.date() to format that new seconds into individual date components.


It seems long winded, but if you do it by subtracting 7 from the day and end up with a negative number, then you have to figure out what that new day is in the previous month (which could be 28, 29, 30 or 31 days long) and then subtract one from the month and check to make sure that didn't go negative and if it does, change the month to December and subtract one from the year.  That's a whole lot more work with all the if statements you have to write vs:


convert to seconds

subtract (7 days * seconds in a day)

convert back to m/day/year.


and the conversion is pretty simple os.* APIs.




[TOPIC: post.html]


[GLOBAL: userInfoPane.html]
  • Observer

  • 7 posts
  • Corona SDK

Thank you to everyone getting back to me super fast in Slack. I needed to get this done so this was a great help. 


Here are some other suggestions made


1.) StarCrunch - https://github.com/daurnimator/luatz - Time, date and Timezone



2.) SGS -  I always store dates in epoch time
then to subtract 7 days you can simply do `myDate = myDate - ( 7 * 24 * 60 * 60)` from SGS
3.) Depilz - I use the penlight lib for a loot of stuff
Date is one of them
I recomend to check the List, Tablex and Date classes