简体   繁体   中英

How to perform date operations in bash

Basically, I want to take a time, and day of the week, in UTC+8, and adjust the datetime object to a given UTC offset, within bash, I don't have any code to show because I'm not sure how to start attempting this in the first place honestly

(I'm writing a custom script for a friend who lives in UTC+8 and want to make the input as easy as possible for them, basically they just give it a time in their timezone, and a day of the week, and it'll tell them what date and time that'll be in a different timezone, for an overarching purpose)

For a reference, look at the section 1 of the manual page for "date":

In your shell, just type: man 1 date

or see the online man page: https://man7.org/linux/man-pages/man1/date.1.html

One way is to parse the date into the number of seconds since epoch (since 1970), and then convert that number of seconds into the format you want:

For example:

$ date +%s  --date='2022-12-27 11:30:17 +008'
1672140137

$ date +%c --date='@1672140137'
Tue 27 Dec 2022 06:22:17 AM EST

or you could also convert to ISO format then back to local time

$ date -Iseconds --date='TZ="GMT" 2022-12-22 11:33:44 +08'
2022-12-21T22:33:44-05:00
$ date --date='2022-12-21T22:33:44-05:00'
Wed 21 Dec 2022 10:33:44 PM EST

I hope this helps you get started with some ideas for converting to/from different timezones.

Also, to help with user input, you can show the current month calendar using cal

$ cal
   December 2022      
Su Mo Tu We Th Fr Sa  
             1  2  3  
 4  5  6  7  8  9 10  
11 12 13 14 15 16 17  
18 19 20 21 22 23 24  
25 26 27 28 29 30 31  
                      
$ date --date='Fri 08:30'
Fri 30 Dec 2022 08:30:00 AM EST

In the above example, I specified "Fri 08:30" which gets set to the next Friday at 08:30 in the morning for my local timezone.

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