Add Some Specific Time While Using the Linux Command "Date"

Add some specific time while using the linux command date


On Linux

Just use -d (or --date) to do some math with the dates:

date -d '+1 hour' '+%F %T'
# ^^^^^^^^^^^^

For example:

$ date '+%F %T'
2013-04-22 10:57:24
$ date -d '+1 hour' '+%F %T'
2013-04-22 11:57:24
# ^

On Mac OS

Warning, the above only works on Linux, not on Mac OS.

On Mac OS, the equivalent command is

date -v+1H

Add x seconds to the current date in Linux

You can add 5 seconds to the current time in one command using date -s "5 seconds".

The full manual regarding all of the date input formats that all of GNU coreutils accepts can be found online at https://www.gnu.org/software/coreutils/manual/html_node/Date-input-formats.html.

Trying to add 1 day to a timestamp in bash script but it's only adding 19 hours

date's free-form date parser seems to get pretty confused with + something at the end of a date-time. All the gory details here: https://www.gnu.org/software/coreutils/manual/html_node/Date-input-formats.html

I get similar results:

$ tail -n 1 run_dates.txt
2018-09-21 20:42:57
$ date -d "$(tail -n 1 run_dates.txt) +1 day" '+%F %T'
2018-09-22 15:42:57

but if you ask for "tomorrow" instead of "+1 day":

$ date -d "$(tail -n 1 run_dates.txt) tomorrow" '+%F %T'
2018-09-22 20:42:57

How to increment a date in a Bash script

Use the date command's ability to add days to existing dates.

The following:

DATE=2013-05-25

for i in {0..8}
do
NEXT_DATE=$(date +%m-%d-%Y -d "$DATE + $i day")
echo "$NEXT_DATE"
done

produces:

05-25-2013
05-26-2013
05-27-2013
05-28-2013
05-29-2013
05-30-2013
05-31-2013
06-01-2013
06-02-2013

Note, this works well in your case but other date formats such as yyyymmdd may need to include "UTC" in the date string (e.g., date -ud "20130515 UTC + 1 day").

Command to get time in milliseconds

date +%s%N returns the number of seconds + current nanoseconds.

Therefore, echo $(($(date +%s%N)/1000000)) is what you need.

Example:

$ echo $(($(date +%s%N)/1000000))
1535546718115

date +%s returns the number of seconds since the epoch, if that's useful.

BASH date command: can't re-combine date and time

When getting your date use this format instead:

#split date and time
dldate="$(date -d "$dnow1" +"%Y-%m-%d")"

How can I get the current date and time in the terminal and set a custom command in the terminal for it?

The command is date

To customise the output there are a myriad of options available, see date --help for a list.

For example, date '+%A %W %Y %X' gives Tuesday 34 2013 08:04:22 which is the name of the day of the week, the week number, the year and the time.



Related Topics



Leave a reply



Submit