4

Can someone help me understand why I get "-1" returned by mktime in the following code. Thanks.

#!/usr/local/bin/bash
f_name="crap.stat"
S_Date="2012-02-10"
E_Date="2012-02-13"

gawk -F '\t' -v s_date="$S_Date" -v e_date="$E_Date" 'BEGIN {s_time = mktime(s_date);e_time = mktime(e_date);print s_time, e_time}' $f_name
Shuvo Shams
  • 633
  • 4
  • 10
  • 22

1 Answers1

6

You have to use a specific format for that function. Here your code fixed:

#!/usr/local/bin/bash
f_name="crap.stat"
S_Date="2012-02-10"
E_Date="2012-02-13"

gawk -F '\t' -v s_date="$S_Date" -v e_date="$E_Date" '
  BEGIN { 
    gsub( /-/, " ", s_date ); 
    s_date = s_date " " 00 " " 00 " " 00; 
    s_time = mktime(s_date);
    gsub( /-/, " ", e_date ); 
    e_date = e_date " " 00 " " 00 " " 00;
    e_time = mktime(e_date);
    print s_time, e_time
  }
' $f_name

Result:

1328828400 1329087600

It must be next format: YYYY MM DD HH MM SS[ DST], so I replace - with spaces and append zeros for the time.

Birei
  • 35,723
  • 2
  • 77
  • 82
  • my datafile has the format $Date $val and $Date is in format "yyyy-mm-dd" so, I need mktime to generate date in that format for comparison – Shuvo Shams Mar 19 '12 at 15:31
  • Thanks, the comparison worked even without using the mktime, strange? – Shuvo Shams Mar 19 '12 at 15:41
  • @ShuvoShams: One advantage of the ISO8601-like (ISO8601 has timezone stuff in as well) is that a string comparison works... (Since it is arranged from most significant to least significant) (Leading zeroes are required for string comparisons to work though) – Gert van den Berg Jun 01 '15 at 09:33