Bash: compute dates

Often I found myself in the need of computing some math on dates. For example what is 10 weeks from a given date? Rather than opening a calendar and start counting you can quickly open a bash shell.

Example: what’s 6th of June 2017 plus 10 weeks?

$ date -j -v '+10w' -f '%Y-%m-%d' '2017-06-06'
Tue 15 Aug 2017 10:00:20 BST
Advertisements

MySQL add 3 years to a date

It may happens if you are silly like me, that you just inserted a lot of records and then realized that you have inserted a mistaken date. In my case the date was a 3 years earlier than the required.

In order to fix it rapidly with mysql you can use the date_add function. Following a quick ad self explaining statement

update <table> set <field>=date_add(<field>,interval 3 year) where id>3289;

[bash] format date

It happens often a script I have the needs to append a simple timestamp in the format of YYYYMMDDHHMMSS to a generated file.

It’s very easy to get it to work in pure bash, without perl script and similia. Just use the native date command with his format option. Easy as drinking a glass of water, the command is (for the format above)

$ date +”%Y%m%d%H%M%S”

for the full detail of the format arguments, refer to the man page.

A simple usage in script is

#!/bin/bash
set -e

NOW=`date +”%Y%m%d%H%M%S”`
FILE=my-cool-file-${NOW}.txt

echo $FILE