I have a date in a the %c
format (could be any other) and I need to use it in the date command. %c
is NOT the American format. It is the German one because it's a German server. This also did not work properly on an American server. (Locales set to German or American)
This does not work (error included):
user@server:~$ NOW=$(date +%c); echo $NOW
Do 19 Dez 2013 22:33:28 CET
user@server:~$ date --date="$NOW" +%d/%m/%Y
date: ungültiges Datum ?Do 19 Dez 2013 22:33:28 CET“
(date: ungültiges Datum ?Do 19 Dez 2013 22:33:28 CET“ = date: invalid date ?Do 19 Dez 2013 22:33:28 CET“
)
The difficulty is that I don't know which locale or even whci dateformat will be used later since the user can set their own format. So a simple specific parsing solution ist not really going to work!
But how do I do it?
To gerneralize the issue:
If I have a date format format1
(which could be any or at least one that can be reversed) I can use date to get a formatted date. But if I want to format it to another date (format2
) how do I do it?
Any solution using anything else than the coreutils is pointless since I am trying to develop a bash script for as many unix machines as possible.
DATE=$(date "+$format1")
date --date="$DATE" "+$format2" # Error in most cases!
This is needed because I have a command which the user can give a date format. This date string is going to be displayed. But in a later step I need to convert this date string into another fixed one. I can manipulate the whcih format the command will get and I can maniplulate the output (or what the user will see).
I cannot run the command twice because it is very time consuming.
Update:
I have found something like a solution:
# Modify $user_format so it can be parsed later
user_format="$user_format %s"
# Time consuming command which will print a date in the given format
output=$(time_consuming_command params "$user_format" more params)
# This will only display what $user_format used to be
echo ${output% *}
# A simple unix timestamp parsing ("${output##* }" will only return the timestamp)
new_formated_date=$(date -d "1970-01-01 ${output##* } sec UTC" "+$new_format")
This is working and might be helpful to others. So I will share this with you.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…