Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert GMT timestamp to local time using Bash and GNU tools

Tags:

linux

bash

I am getting results to a log file that contain a line like this:

date: Sat, 12 Dec 2020 22:33:34 GMT

I want to use only Bash and GNU tools on my Ubuntu Linux box if possible to convert this to my local time "Eastern" or Michigan/Detroit. It should work even on Daylight Saving Time or if past/before Midnight. I want the result stored in a variable in a common format such as 2020-12-01 for December 1, 2020. One variable for the military time, a second for the date would probably be best. I can calculate the "Sat/Sun/Mon/etc" and probably don't need that anyway.

I would expect the "cut" command could separate out the different fields, but how to deal with GMT?

#!/bin/bash

datime="date: Sat, 12 Dec 2020 22:33:34 GMT"

#magic happens

echo dalocaltime is $dalocaltime and dalocaldate is $dalocaldate

results:

dalocaltime is 14:20:33 and dalocaldate is 2020-01-30
like image 267
MarkT9 Avatar asked Oct 27 '25 05:10

MarkT9


1 Answers

This works for me, but I can't explain the ${datime#* } part

datime="date: Sat, 12 Dec 2020 22:33:34 GMT"
dalocaltime=$(date -d "${datime#* }" '+%R')
dalocaldate=$(date -d "${datime#* }" '+%Y-%m-%d')
echo dalocaltime is $dalocaltime and dalocaldate is $dalocaldate
like image 56
MarkT9 Avatar answered Oct 28 '25 20:10

MarkT9



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!