Convert date to different timezone + format change
It doesn't look like date
supports an input format string. As such you won't be able to just go ahead and pass the string to date. The man page state that it accept the usual formats so maybe your locale setting could influence this but I'm not sure about that.
Further more lets have a look at your script:
#!/bin/bash
sec=$(TZ="UTC" date +'%s' -d "$1")
$(TZ="Europe/Helsinki" date -d "@$sec" "+%Y:%m:%d %H:%M:%S")
What happens here is that you convert the $1
parameter to a Linux time stamp and then convert it again into a string you want. One possible approach to make this work with your input would be to reformat the $1
string parameter.
You could do this as an example by using sed
with a suitable regex. Beware that you should make sure that you have a valid string beforehand and that any format changes might break this.
#!/bin/bash
intputdate=$(echo $1 | sed -re 's/([0-9]{2})\.([0-9]{2})\.([0-9]{4})/\3-\2-\1/')
sec=$(TZ="UTC" date +'%s' -d "$intputdate")
echo $(TZ="Europe/Helsinki" date -d "@$sec" "+%Y:%m:%d %H:%M:%S")
Edit: Not having the wrong variable names certainly helps.
Related videos on Youtube
user3647376
Updated on September 18, 2022Comments
-
user3647376 over 1 year
I have a log file with timestamps in format of "22.09.2016 08:22:54" ("+%Y:%m:%d %H:%M:%S"). This timestamp is in UTC timezone.
Now I have to convert this timestamp to Europe/Helsinki timestamp using bash script.
I have this script which makes the conversion as I want.
#!/bin/bash sec=$(TZ="UTC" date +'%s' -d "2015-05-20 18:05:02") TZ="Europe/Helsinki" date -d "@$sec" "+%Y:%m:%d %H:%M:%S"
This works fine but the date "input" format ( -d "2015-05-20 18:05:02" ) is different format comparing to my log timestamp format.
I would like to change this script to something like this..
#!/bin/bash sec=$(TZ="UTC" date +'%s' -d "$1") TZ="Europe/Helsinki" date -d "@$sec" "+%Y:%m:%d %H:%M:%S"
Where the $1 can be in the original date format of my log file "22.09.2016 08:22:54" ("+%Y:%m:%d %H:%M:%S").
I cannot make this to work.. Can someone help me with this one.. Thank you
EDIT:
I have tried something like this and many other combinations..
#!/bin/sh sec=$(TZ="UTC" date +'%s' "+%Y:%m:%d %H:%M:%S" -d "$1") TZ="Europe/Helsinki" date -d "@$sec" "+%Y:%m:%d %H:%M:%S"
but his ends up with error..
date: extra operand ‘+%Y:%m:%d %H:%M:%S’ Try 'date --help' for more information. date: invalid date ‘@’
-
Seth over 7 yearsDid you try to set a format for your first line?
-
user3647376 over 7 yearsyes.. I have tried this.. #!/bin/sh sec=$(TZ="UTC" date +'%s' "+%Y:%m:%d %H:%M:%S" -d "$1") TZ="Europe/Helsinki" date -d "@$sec" "+%Y:%m:%d %H:%M:%S" but his ends up with error.. date: extra operand ‘+%Y:%m:%d %H:%M:%S’ Try 'date --help' for more information. date: invalid date ‘@’
-
-
Vomit IT - Chunky Mess Style over 6 yearsRead over "Why do I need 50 reputation to comment" to ensure you understand how you can start commenting.