4

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?

2

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.

| improve this answer | |
  • 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 '17 at 4:23
6

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
| improve this answer | |
  • 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 '17 at 4:18
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?

| improve this answer | |
  • If you need now in Taipei, this DATE=$(TZ=Asia/Taipei date +"%F %H:%M") shoud be easier – Alexey Ten Jul 24 '17 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 '17 at 10:22
  • @AlexeyTen 's thanks I think this is more accurate – Ramperto P Pasaribu Jul 24 '17 at 10:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.