YYYY-MM-DD format date in shell script
#1
I'm working on a bash script where I need to manipulate dates, but I'm having trouble formatting the date output as I need it. The default $(date) command outputs the full date string, which includes the day of the week, month, day, time, timezone, and year. This is far more information than I require for my script, and it causes unnecessary complication for my use case.
Specifically, I need the date formatted as YYYY-MM-DD. From what I've found in the man pages and various forums, the date command can be formatted with different options, but I'm not clear on the exact syntax to achieve the format I want.
Here's what the default date command gives me:

Code:
date_output = $(date)
echo $date_output

The result is something like this: Tue Mar 14 15:20:13 PDT 2023
Can anyone provide me with the correct formatting options for the date command to get the date in YYYY-MM-DD format?
Reply
#2
In the date command, you can format the output using the '+format' option, where 'format' consists of various placeholders for year, month, day, etc. There is a specific placeholder for year (%Y), month (%m), and day (%d).
To combine these, you'd use the date command as follows:


This will output the date in the format you're looking for: YYYY-MM-DD.
Reply
#3
I see, so by including the +%Y-%m-%d option with the date command, it outputs in the format I want. This works perfectly for my needs; however, I was also wondering how to handle the same format with a specific timestamp.
For instance, if I have an epoch timestamp and I want to convert it to the YYYY-MM-DD format, how would I go about that?
Reply
#4
You can use the date command with the '-d' option followed by the '@' symbol and your epoch timestamp. The syntax looks like this:

Code:
timestamp = 1678832400
formatted_date_from_timestamp = $(date - d @$timestamp + % Y - % m - % d)
echo $formatted_date_from_timestamp

Replacing the 'timestamp' variable with your epoch time will give you the desired format.
Reply
#5
Applying your advice, the complete solution to format the current date as well as an epoch timestamp into YYYY-MM-DD would then be:

Code:
timestamp = 1678832400
formatted_date_from_timestamp = $(date - d @$timestamp + % Y - % m - % d)
echo $formatted_date_from_timestamp
Reply
#6
Exactly, those blocks of code will do what you need. Make sure to replace 'timestamp' with the actual epoch timestamp you need to format. These code snippets can be copied directly into your script, and they should work as expected.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)