0

I can't find the right syntax to convert a string date in epoch timestamp.

The script is:

date -d '2012-03-02 22:00 EDT' +%s
DATEJ=`echo -n \'2012-03-02 22:00\'`
echo $DATEJ
date -d $DATEJ EDT +%s

and the result is

[gg@raspi8 ~]$ CNVDATTS
1330740000  
'2012-03-02 22:00'  
date: opérande supplémentaire « EDT »  
Saisissez « date --help » pour plus d'informations.  

Where is the fault?

It seems that the variable DATEJ does not give the same as the string in the 1st line. If I don't write EDT, the error is same but mention +%s.

2
  • What type of Unix are you running on?
    – Kusalananda
    Aug 15, 2019 at 10:00
  • 1
    what's the point of the echo -n? why not just DATEJ='2012-03-02 22:00'? Also, you need double-quotes when you use $DATEJ - e.g. date -d "$DATEJ EDT" +%s, otherwise date will get three arguments $DATEJ, EDT, and +%s instead of two....that's why it's complaining about the extra argument (i don't speak or read french but i can make an uneducated guess :)
    – cas
    Aug 15, 2019 at 10:20

2 Answers 2

1

The problem here seems to be with the single-quotes in $DATEJ. Your variable imposes them.

Change that to

DATEJ=`echo -n "2012-03-02 22:00"`

and in the final command:

date -d "$DATEJ EDT" +%s

This will work:

$ date -d '2012-03-02 22:00 EDT' +%s
1330740000
$ DATEJ=`echo -n "2012-03-02 22:00"`
$ echo $DATEJ
2012-03-02 22:00
$ date -d "$DATEJ EDT" +%s
1330740000

EDIT

Actually, you don't need to echo the date, unless your script imposes so, so the variable $DATEJ can simply be put as

DATEJ="2012-03-02 22:00"
0

Hopefully the following will help you or someone else looking for solution.

The date string can be of format mm/dd/yyyy hh:mm:ss zzz or any equivalent. For ex: "06/10/2021 21:00:00 EST" or "06/10/2021 09:00:00 EST" TZ data is optional.

You can give the following command to get epoch timestamp:

date -d "06/10/2021 00:00:00 EST" +"%s"

OR

you can pass the string in a variable, for ex:

date_string="06/10/2021 00:00:00 EST"
date -d "$date_string" +"%s"

For your specific problem, following should work:

date -d '2012-03-02 22:00 EDT' +%s
DATEJ=`echo -n "2012-03-02 22:00"`
echo $DATEJ
date -d "$DATEJ EDT" +%s

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.