1

I know how many seconds have passed since last sunday midnight UTC. Is it possible to retrieve current UTC date and time from this information?

I have an idea as to how to get time (modulo) but what about date? I can't wrap my head around it because of leap days, years, etc..

c0dehunter
  • 6,412
  • 16
  • 77
  • 139
  • A library might simplify things by abstracting away the gory details of time keeping. Of course, that depends on your language and I don't know which you're using – jDo Mar 29 '16 at 06:48
  • I've added some tags. So, I'm working on embedded Linux with pretty limited options considering library usage. I'm more or less limited to c++ (C++03) built-in metods and [BusyBox](https://busybox.net/downloads/BusyBox.html). – c0dehunter Mar 29 '16 at 06:58
  • 1
    Ouch! I was hoping for an easy `import datetime; datetime.fix_all_my_problems()` python solution :D The clock/calendar maths shouldn't be too hard but leap days/years might be another matter (as you clearly know). Some SO links: [converting-number-of-days-to-years-including-leap-years](https://stackoverflow.com/questions/11609769/efficient-algorithm-for-converting-number-of-days-to-years-including-leap-years) and [leap-year-calculation-homework](https://stackoverflow.com/questions/12591853/leap-year-calculation-homework) – jDo Mar 29 '16 at 07:12
  • I don't think it's possible to get date anyways. – c0dehunter Mar 29 '16 at 07:44
  • Maybe not. [This question](https://stackoverflow.com/questions/9076494/how-to-convert-from-utc-to-local-time-in-c?rq=1) has some good code and interesting comments that really highlight the issues. I know you're dealing with UTC rather than "UTC to local time", but it's a good read – jDo Mar 29 '16 at 07:59

1 Answers1

1

You can only retrieve a date of point B with B = A + n if you know the date for A. This calculation is not trivial in no aspect, as our calendar is so complex. Btw: last sunday is only a relative date.

With BusyBox you can try to use the date tool that is able to do calculations such as

date +"%s" --date="last sunday"

for you. For example (with n = number of seconds passed from last sunday)

A_s=$(date +"%s" --date="last sunday")
let 'B_s=A_s + n'
date -u --date="@""${B_s}"

called as a shell script from your code.

ikrabbe
  • 1,909
  • 12
  • 25