Tuesday, May 14, 2024
 Popular · Latest · Hot · Upcoming
0
rated 0 times [  0] [ 0]  / answers: 1 / hits: 1861  / 2 Years ago, sun, october 23, 2022, 11:32:14

I need to add 84 hours to a specific starting UTC date. The start UTC date is the current date but the starting hour is not. The code below works great until the end of the month when it can't convert to the next month or the end of the year when it can't convert years.



#Date variables

export start_year=$(date -u +%Y)
export start_mon=$(date -u +%m)
export start_monc=${start_mon#0} # strip leading 0
export start_day=$(date -u +%d)
export start_dayc=${start_day#0} # strip leading 0
export start_hour=$fhour # -------THIS IS EITHER 6, 12, 18, or 0


And here is where the problems start to appear:



export end_hour=$(( ($start_dayc*24+84)%24 ))
export end_day=$(( $start_dayc+((($start_dayc*24)+84)/24) ))
export end_mon=$(date -u +%m -d '((($start_dayc*24)+84)/24) days')
export end_year=$(date -u +%Y)


The extra variable start_monc is for calculation since the leading zero creates problems. The ending components need to be broken up like they are. My last resort is creating a series of if statements to change month/year appropriately.



Any suggestions to fix my month/year conversion problem?



Thanks once again for putting up with my questions, great resource on this website.


More From » bash

 Answers
5

I would do this:



add_84_hours() {
local datestamp=$1
local start_hour=$2
local epoch=$(date -ud "$datestamp $start_hour:00" +%s)
date -ud "@$(( epoch + 84*3600 ))" +"%Y %_m %e %k"
}


Let's see what it returns:



$ add_84_hours now 18
2014 2 28 6
$ add_84_hours 2014-02-26 18
2014 3 2 6
$ add_84_hours 2016-02-26 18 # leap year
2016 3 1 6


To save those values to variables:



read end_year end_month end_day end_hour < <(add_84_hours now 18)
printf "%s
" "$end_year" "$end_month" "$end_day" "$end_hour"




2014
2
28
6

[#26832] Monday, October 24, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tocklftime

Total Points: 110
Total Questions: 109
Total Answers: 100

Location: Mayotte
Member since Mon, Sep 12, 2022
2 Years ago
tocklftime questions
Wed, Feb 1, 23, 21:50, 1 Year ago
Tue, Oct 4, 22, 21:42, 2 Years ago
Sun, Jul 25, 21, 10:43, 3 Years ago
;