linuph
linuph

Reputation: 81

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

Linux v2.4/Bash v3.2/GNU utils/date command version 5.0

I'm struggling with the date command. In a BASH application, the user can set date and time separately, resulting in separate variables for date and time. Further on, these variables are re-combined but this appears not be palatable for the date command: I get a different date back. Time is the same, however. Testing code:

#!/bin/bash
dnow1="$(date)"
echo "1 $dnow1"                             # --> Sat Sep 14 16:31:48 EDT 2013
#split date and time
dldate="$(date -d "$dnow1" +"%d-%m-%Y")"
echo "2 $dldate"                            # --> 14-09-2013
dltime="$(date -d "$dnow1" +"%H:%M:%S")"
echo "3 $dltime"                            # --> 16:31:48
#try to re-combine date and time
string="${dldate} ${dltime}"
echo "4 $string"                            # --> 14-09-2013 16:31:48
dnow2="$(date -d "$string")"
echo "5 $dnow2"                             # --> Thu Mar 5 16:31:48 EST 2020

I must be missing something here. Can anyone enlighten me? Thanks!

Note: I'm working an original XBOX that has few/low resources so there's no room for other solutions like Python. I'm a 'bashist' anyway so it must be BASH!

Edit: corrected time format. Thanks Mat. As to "$(....)" I have made it a habit to double quote wherever possible.

Upvotes: 0

Views: 2881

Answers (3)

konsolebox
konsolebox

Reputation: 75588

When getting your date use this format instead:

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

Upvotes: 1

linux_fanatic
linux_fanatic

Reputation: 5177

First of all using -d won't work in 14-09-2013 fashion, you can easily set date and time with one command and put it into variable. eg, just try this below on shell and then you can put into shell script.

date --date="Feb 2 2014 13:12:10"  
Sun Feb  2 13:12:10 PST 2014

Upvotes: 0

evading
evading

Reputation: 3090

From GNU date manual

The output of the date command is not always acceptable as a date string, not only because of the language problem, but also because there is no standard meaning for time zone items like ‘IST’. When using date to generate a date string intended to be parsed later, specify a date format that is independent of language and that does not use time zone items other than ‘UTC’ and ‘Z’.

Upvotes: 0

Related Questions