Skip to content
Fix Code Error

YYYY-MM-DD format date in shell script

March 13, 2021 by Code Error
Posted By: Anonymous

I tried using $(date) in my bash shell script, however, I want the date in YYYY-MM-DD format.
How do I get this?

Solution

In bash (>=4.2) it is preferable to use printf’s built-in date formatter (part of bash) rather than the external date (usually GNU date).

As such:

# put current date as yyyy-mm-dd in $date
# -1 -> explicit current date, bash >=4.3 defaults to current time if not provided
# -2 -> start time for shell
printf -v date '%(%Y-%m-%d)Tn' -1 

# put current date as yyyy-mm-dd HH:MM:SS in $date
printf -v date '%(%Y-%m-%d %H:%M:%S)Tn' -1 

# to print directly remove -v flag, as such:
printf '%(%Y-%m-%d)Tn' -1
# -> current date printed to terminal

In bash (<4.2):

# put current date as yyyy-mm-dd in $date
date=$(date '+%Y-%m-%d')

# put current date as yyyy-mm-dd HH:MM:SS in $date
date=$(date '+%Y-%m-%d %H:%M:%S')

# print current date directly
echo $(date '+%Y-%m-%d')

Other available date formats can be viewed from the date man pages (for external non-bash specific command):

man date
Answered By: Anonymous

Related Articles

  • How to prevent scrolling the whole page?
  • Vue element-ui formatter – how to display html?
  • How can I parse / create a date time stamp formatted…
  • Getting infinite loop after entering 2 objects to…
  • How to Customize the time format for Python logging?
  • How to take just the current time (hh:mm:ss format)…
  • Java string to date conversion
  • How to turn off the Eclipse code formatter for…
  • Swift - How to convert String to Double
  • OpenCL - Approximation of Pi via Monte Carlo…
  • SDL_SetRenderTarget() hangs for a while if multiple…
  • Format Instant to String
  • Converting NSString to NSDate (and back again)
  • Convert Java Date to UTC String
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • How to change the color of vaadin-select-text-field…
  • C free(): invalid pointer
  • Backbone.js - Using new() in Model defaults -…
  • How to throw std::exceptions with variable messages?
  • How to parse a date?
  • Get day of week using NSDate
  • Smart way to truncate long strings
  • Rust calling fmt function directly
  • Current time formatting with Javascript
  • Segmentation fault - invalid memory reference…
  • How to make a SIMPLE C++ Makefile
  • Simple logical operators in Bash
  • JS passing the forEach variable to the lookup function
  • anaconda/conda - install a specific package version
  • Dynamically update values of a chartjs chart
  • What is your most productive shortcut with Vim?
  • How to get $HOME directory of different user in bash script?
  • What's a concise way to check that environment…
  • Check number of arguments passed to a Bash script
  • Convert NSDate to NSString
  • Backbone js collection of collections issue
  • What does "-ne" mean in bash?
  • Fast way of finding lines in one file that are not…
  • What's the difference between Instant and LocalDateTime?
  • Copy a file in a sane, safe and efficient way
  • "No such file or directory" error when executing a binary
  • How to permanently set $PATH on Linux/Unix?
  • Extending the defaults of a Model superclass in Backbone.js
  • Apexchart tooltip
  • Simplest way to create Unix-like continuous pipeline…
  • Serializing/deserializing with memory stream
  • fork() and wait() with two child processes
  • For-each over an array in JavaScript
  • How to use shell commands in Makefile
  • How do you get the list of targets in a makefile?
  • delete item in array of struct that has char array…
  • How to debug a bash script?
  • java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy
  • `set -o posix` Not Working in Bash 5.0.17 on WSL2…
  • What is the purpose of the : (colon) GNU Bash builtin?
  • Why does C++ code for testing the Collatz conjecture…
  • Logging multiple scripts from the same directory in python
  • Logging best practices
  • Convert Date/Time for given Timezone - java
  • strange behavior with sed or xargs
  • How to run a shell script on a Unix console or Mac terminal?
  • Date range picker in Ember.view
  • Implementation of user defined array on stack and/or…
  • Aurelia UX showcase app fails to load
  • AtmelStudio recipe for target *.elf failed
  • How are zlib, gzip and zip related? What do they…
  • Debugging the error "gcc: error:…
  • How to obtain the start time and end time of a day?
  • Aurelia app is not launched using au run cli command
  • What are the special dollar sign shell variables?
  • Parsing Timezone String Date into Java's Instant
  • Pandas how to split vlaues of every column based on colon
  • What is the difference between Cygwin and MinGW?
  • How to write an application to control a driver…
  • How to save local data in a Swift app?
  • Format LocalDateTime with Timezone in Java8
  • Changing PowerShell's default output encoding to UTF-8
  • How do I read the source code of shell commands?
  • Unit test by mocking external DLL using Moq in C#
  • Sort a list in C# by custom index and sameness
  • Highcharts make positive numbers in ranges of green…
  • moment.js - UTC gives wrong date
  • How to change Vuetify calendar date format
  • How to Control boolean field in react-bootstrap-table-next
  • Problems with local variable scope. How to solve it?
  • Vue js apply filter on v-model in an input field
  • ASP.NET Core return JSON with status code
  • Hybris business process polling
  • Best practices for circular shift (rotate) operations in C++
  • First echo missing when using bash -c over SSH
  • Creating a custom counter in Spark based on…
  • Call the javascript function and render element in Svelte
  • Reliable way for a Bash script to get the full path…
  • C# Interfaces. Implicit implementation versus…
  • What are the real-world strengths and weaknesses of…
  • How to change the integrated terminal in visual…
  • Convert string to date then format the date
  • Invalid date in safari
  • Difference between single and double quotes in Bash
  • In Backbone.js how can I get Model superclass…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to get a Docker container’s IP address from the host

Next Post:

How to get current time and date in Android

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error