简体   繁体   中英

How to convert years to days (in the past)?

I want convert years to days (in the past) with a Linux command. For example:

  1. The user give number: 10 years ago

  2. The program should calculate the sum of the days in 10 years ago (ex: 10*12*31 (years/month/days) --> 3720 days).

  3. The program sum it with current days from begin this year (ex: 3720 + 223) and return it.

这将为您提供一年的日期,即距现在的10年:

date -d '+10 years' +"%j"

The current time in seconds since 1970/01/01 (The Unix 'day 1'):

dnow=$(date +"%s")

The time exactly 10 years ago:

dthen=$(date -d '-10 years' +"%s")

Calculate today's day in the year:

dity=$(date +"%j")

Then just subtract one from the other, divide by the number of seconds in a day, and add today's day-in-the-year:

timespan=$(( (dnow - dthen) / (24*60*60) + dity ))

You should set $dnow after $dthen , to avoid an off-by-one error.

I'm not sure why anyone would want to do this, so if I've misinterpreted your question, please come back to us.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM