7

I am working on Linux Ubuntu, and I want a bash script whose output is to convert the timezone 7 hours in advance from my server time.

My server time:

Mon Jul 23 23:00:00 2017

What I want to achieve:

Mon Jul 24 06:00:00 2017

I have tried this one in my bash script:

#!/bin/bash

let var=$(date +%H)*3600+$(date +%M)*60+$(date +%S)
seven=25200
time=$(($var+$seven))

date=$(date --date='TZ="UTC+7"' "+%Y-%m-%d")
hours=$(date -d@$time -u +%H:%M:%S)

echo "$date" "$hours"

the output was:

2017-07-23 06:00:00

The hours works, but the date still matches the server date. Is there another way to solve this?

3 Answers 3

14

You can change the time zone for the entire script by changing the TZ environment variable early in the script. It can be overridden on individual commands.

For example this script

#!/bin/bash
export TZ=Australia/Sydney

date
TZ=US/Pacific date
date

Will output

Sun 30 Jul 21:56:25 AEST 2017
Sun 30 Jul 04:56:25 PDT 2017
Sun 30 Jul 21:56:25 AEST 2017
2
  • thanks but I don't want "AEST" or "PDT" on my output, well I have found the solution, I am using DATE=$(TZ=Asia/Bangkok date +"%FI%H:%M")
    – Ramperto P Pasaribu
    Jul 31, 2017 at 4:18
  • Be careful that the timezone you're interested in is entered accurately, or date will silently default to UTC. TZ=foo date yields Wed Aug 5 19:30:05 foo 2020 (which happens to be UTC).
    – enharmonic
    Aug 5, 2020 at 19:34
3

Taking your question literally, if you just want to get a date string for 7 hours later than the current time in the current zone, that's easy:

date -d "7 hours" "+%Y-%m-%d %H:%M:%S"

If what you're really wanting to do is pull the local date/time in some other timezone, though, then you'd be better off following the advice in some of the other answers.

1
  • thanks I tried this one and it works, and yeah I am trying to pull the local time zone in other timezone, it works using this DATE=$(TZ=Asia/Bangkok date +"%FI%H:%M")
    – Ramperto P Pasaribu
    Jul 31, 2017 at 4:23
3

Have you looked in the quoting section in man bash ?
I believe something like DATE=$( date --date="TZ=\"Asia/Taipei\" $TIME" +%F\ %H:%M ) is what you're looking for. Can anyone second that for me?

3
  • If you need now in Taipei, this DATE=$(TZ=Asia/Taipei date +"%F %H:%M") shoud be easier
    – Alexey Ten
    Jul 24, 2017 at 9:39
  • Okay I will try this and look for the result tomorrow. Thanks for the reply by the way, hope it works
    – Ramperto P Pasaribu
    Jul 24, 2017 at 10:22
  • @AlexeyTen 's thanks I think this is more accurate
    – Ramperto P Pasaribu
    Jul 24, 2017 at 10:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .