Adding time to date time in UNIX shell scipting


Login or Register for Dates, Times and to Reply

 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Adding time to date time in UNIX shell scipting
# 1  
Adding time to date time in UNIX shell scipting

I needed some help in adding a duration (in seconds) to a start time (in hhmmss format) and a start date (in mmddyy format) in order to get an end date and end time. The concept of a leap year is also to be considered while incrementing the day. The code/ function that I have formed so far is as follows, but there appears to be an error in the function calling. I also wanted to check if this script designed by me is full proof.

Code:
MIN_TIME = start_time; 
                        secs=substr(MIN_TIME,5,2);
            mins=substr(MIN_TIME,3,2);
            hrs=substr(MIN_TIME,1,2);
            durn=p;
            d=substr(MIN_DATE,3,2);
            m=substr(MIN_DATE,1,2);
            y=substr(MIN_DATE,5,2);
            date=d;
            mone=m;
            ye=y;
            durn=p;

 function incrementday (d, m, y)

      {  if(d<28)                                       #increment day
        { date=d+1;
        mone=m;
        ye=y;}

        else if(d == 28)
        { if(m==2)
            { if(y%4==0)
                {date=d+1; mone=m; ye=y;}
          else {date=1;
            mone=3;
                ye=y;}}
        else {date = d+1;
         mone=m;
         ye=y;}}
    
    else if(d==29)
    { if(m==2)
        {date=1;
         mone=03;
         ye=y;}
      else
          {date=d+1;
           mone=m;
           ye=y;}}

    else if(d==30)
    { if(m==1||m==3||m==5||m==7||m==8||m==10||m==12)
        {date=d+1;
        ye=y;
        mone=m;}
    else {date=01;
        mone=m+1;
        ye=y;}}

    else {if(m==12)
        {date=01;
        mone=01;
        ye=y+1;
        }
        else {date=01;
            mone=m+1; ye=y;
        }}  }                            #incremented day
          

                
                        sece=secs+durn;
                        
                        if ((sece>=60) && (sece<3600))  # greater than a minute but less than an hour
                          { mine=mins+sece/60;
                                if (mine>=60)
                                    {hre=hrs+1;
                                            if (hre>=24)
                                                {hre=hre-24;
                                                                                                incrementday($d $m $y); }
        
                                     mine=mine-60;}
                            sece=sece%60;}

                        else if ((sece>=3600) && (sece<86400))  #greater than an hour but less than a day
                          { mine=mins+sece/60;
                            if(mine>=60)
                               {hre=hrs+mine/60;
                                if(hre>=24)
                                    {hre=hre-24;
                                                               incrementday($d $m $y); }         
                                mine=mine%60;}
                            sece=sece%60;}

                        else if (sece>=86400)    #greater than a day
                          {mine=mins+sece/60;
                            if (mine>=60)
                                {hre=hrs+mine/60;
                                    {hre=hre-24;
                                                               incrementday($d $m $y);}
                                 mine=mine%60;
                           sece=sece%60;}

---------- Post updated 11-30-12 at 12:07 AM ---------- Previous update was 11-29-12 at 10:40 PM ----------

Let me just elaborate on the variables used in the above code:
Code:
MIN_TIME- start time (in hhmmss format)
MIN_DATE- start date (in mmddyy format)
durn- duration in seconds, 6digits (eg 373687 seconds or 000037 seconds)
d-start day  
m-start month
y-start year
date- end day
mone- end month
ye- end year
secs- starting seconds
mins- starting minutes
hrs- starting hours
sece- ending seconds
mine- ending minutes
hre- ending hours

I hope this information makes it easier to understand the code and help me out in correcting/improvising it.

Last edited by Franklin52; 11-30-2012 at 05:42 AM.. Reason: Code tags
# 2  
Can you please give us more information on what kind of error are you observing while function calling?
# 3  
Date arithmetic

If possible, I always use the inbuilt date command for date arithmetic, as it handles boundary transitions for you. Can't say I have tested it against a leap year but I dare say it works for that too.

If you want to add a duration in seconds to a date then most people convert the date to epoch seconds first. Then it is a question of simple arithmetic to add the duration you want -
Code:
#! /bin/bash
##############################################################
##
## Name                    : m_get_epoch_seconds
## Author                   : Bradley Atkins
## Description            : Return a date time as epoch seconds
## Date                      : 24/09/2012
## Args                      : 1- Time string, e.g. -
##                                    "Jan 1, 1980 00:00:01"
##                                    "January 1, 1980 23:59:59"
##                                    "January 1 1980 23:59:59"
##                                    "1980/1/1 00:00:01"
## Status                    : Reviewed [n]
##                                 Tested [n]
##                                 Released [n]
##############################################################
m_get_epoch_seconds()
{
     [[ $# -gt 1 ]] && return 1
     local TIME="$(date +%s)"
     if [[ $# -eq 1 ]]
     then
            TIME=$(date +%s -d "${1}" 2>/dev/null)
             [[ $? -eq 0 ]] || return 2
     fi
 
     echo "${TIME}"
}
m_get_epoch_seconds "Jan 1, 1980 00:00:01"
m_get_epoch_seconds "January 1, 1980 23:59:59"
m_get_epoch_seconds "January 1 1980 23:59:59"
m_get_epoch_seconds "1980/1/1 00:00:01"
m_get_epoch_seconds

Output
Code:
315532801
315619199
315619199
315532801
1354478648

Similarly, you can use the date command to convert epoch seconds to a valid date format -
Code:
#! /bin/bash
##############################################################
##
## Name                  : m_get_date_from_epoch
## Author                 : Bradley Atkins
## Description          : Convert an epoch time string (secs) to
##                              a human readable date format.
## Date                    : 24/09/2012
## Args                     : 1 - Valid date format string
##                               2 - Time (Epoch Seconds) '@nnnnnnnn'
## e.g. -
##                                  "%d/%m/%Y" "@2147483647"
##                                  "%d/%m/%Y %H:%M:%S" "@2147483647"
##                                  "%d/%m/%y" "@2147483647"
## Status                  : Reviewed [n]
##                               Tested [n]
##                               Released [n]
##############################################################
m_get_date_from_epoch()
{
     ## Usage
     [[ $# -eq 2 ]] || return 1
     local FORMAT= EPOCH= 
     FORMAT="+\"${1}\""
     [[ ${2} =~ ^[@]+[[:digit:]]+$ ]] || return 2
     eval date --date="${2}" "${FORMAT}" || return 3
}
 
m_get_date_from_epoch "%d/%m/%Y" "@2147483647"
m_get_date_from_epoch "%d/%m/%Y %H:%M:%S" "@2147483647"
m_get_date_from_epoch "%d/%m/%y" "@2147483647"

Output -
Code:
19/01/2038
19/01/2038 03:14:07
19/01/38

Hope this helps

Brad
# 4  

Brad, the %s format to date is not standard. GNU and [Free|Net]BSD have it, other variants might not.

These bash functions I just wrote do time arithmetic:
Code:
time2seconds() #@ Calculate no. of seconds from [H]H:[M]M:[S]S result_var
{
  local s hours minutes seconds var IFS=:
  set -- $*
  hours=${1#0}
  minutes=${2#0}
  seconds=${3#0}
  var=${4:-_t2s}
  s=$(( hours * 3600 + minutes * 60 + seconds ))
  printf -v "$var" "%d" "$s"
}

seconds2time() #@ Convert number of seconds to [DAYS ]HH:MM:SS
{
  local s days hours minutes seconds var
  s=$1
  var=${2:-_s2t}
  seconds=$(( s % 60 ))
  hours=$(( s / 3600 ))
  minutes=$(( (s - hours * 3600) / 60 ))

  if [ $hours -gt 24 ]
  then
    days=$(( hours / 24 ))
    hours=$(( hours % 24 ))
  fi

  printf -v "$var" "%s%02d:%02d:%02d" ${days:+"$days "} "$hours" "$minutes" "$seconds"
}

addseconds() #@ To HH:MM:SS add SECS
{
  local time=$1 secs=$2
  time2seconds "$time"
  seconds2time "$(( _t2s + secs ))"
}

They can be combined with the date functions from The Dating Game to solve your problem.
Login or Register for Dates, Times and to Reply

Previous Thread | Next Thread
Thread Tools Search this Thread
Search this Thread:
Advanced Search

Test Your Knowledge in Computers #148
Difficulty: Easy
A free derivative of BSD Unix, 1992BSD, was released in 1992 and led to the NetBSD and FreeBSD projects.
True or False?

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Date time difference in UNIX shell script

There are 2 dates, Tue Oct 1 13:40:19 2013 Sun Sept 30 10:26:23 2013 I have multiple dates like the above one. How do I calculate the date time difference and display in another column in Shell script. Please help. (3 Replies)
Discussion started by: tanmoysays
3 Replies

2. Shell Programming and Scripting

Adding Seconds to UNIX/Epoch-Time

Hello All, I have a Perl script I'm writing where I ask the user to enter a "start time" for something. The "$start_time" will be in the format of: # The Time CLI Option Can be in the format of: --start-time="1day" --start-time="2hours" --start-time="45min" ... (1 Reply)
Discussion started by: mrm5102
1 Replies

3. Solaris

modifying date and time and time zone on solaris 5.10 with (redundant server) veritas

I have a cluster of two Solaris server (veritas cluster). one working and the other is standby I am going to change the date on them , and am looking for a secure solution as it is giving an important service. my opinion is that the active one doesn't need to be restarted (if I don't change the... (1 Reply)
Discussion started by: barry1946
1 Replies

4. UNIX for Dummies Questions & Answers

Adding hours and minutes to current date (Only to date not to time)

Hi, I want to add some hours and minutes to the current date. For example, if the current date is "July 16, 2012 15:20", i want to add 5 hours 30 minutes to "July 16, 2012 00:00" not to "July 16, 2012 15:20". Please help. Thanks! (4 Replies)
Discussion started by: manojgarg
4 Replies

5. UNIX for Dummies Questions & Answers

Converting string date time to unix time in AWK

Id like to convert a date string in the form of sun aug 19 09:03:10 EDT 2012, to unixtime timestamp using awk. I tried This is how each line of the file looks like, different date and time in this format Sun Aug 19 08:33:45 EDT 2012, user1(108.6.217.236) all: test on the 17th ... (2 Replies)
Discussion started by: bkkid
2 Replies

6. Shell Programming and Scripting

Adding date and time to file name

Hi All, i wanted to add date and time to the file names in the same directory so lets say a file in the directory is test.txt then after running the shell script it should be test-15-11-2010.txt. So I used the following script which works, #!/bin/bash thetime=`date +%Y-%m-%d--%H:%M:%S`... (7 Replies)
Discussion started by: cc_at_work
7 Replies

7. UNIX for Dummies Questions & Answers

Adding Date & time stamps to filename

I need to edit the file name with date and time while writing the script. please help. (1 Reply)
Discussion started by: manish.s
1 Replies

8. Shell Programming and Scripting

Convert Epoch Time to Standard Date and Time & Vice Versa

Hi guys, I know that this topic has been discuss numerous times, and I have search the net and this forum for it. However, non able to address the problem I faced so far. I am on Solaris Platform and unable to install additional packages like the GNU date and gawk to make use of their... (5 Replies)
Discussion started by: DrivesMeCrazy
5 Replies

9. UNIX for Dummies Questions & Answers

Adding date and time to a log file

Morning all Im hoping you can help me. We have a nice new oracle server :( and are needing to move some files around for EDI and BACS. The server runs windows but has an app called MKS toolkit installed which give unix commands. (Needed for the oracle stuff) I have had a go using dos commands... (2 Replies)
Discussion started by: ltodd2
2 Replies

10. Shell Programming and Scripting

problem with displaying date and adding time

Hi, I have a log file with contents like 81.49.74.131 - - 81.49.74.131 - - 116.112.52.31 - - 116.112.52.31 - - I need an output like this 81.49.74.131 14/Sep/2008 Time duration: 00:06:00 116.112.52.31 15/Sep/2008 Time duration: 00:00:01 Please anyone suggest a script for this.... (1 Reply)
Discussion started by: FuncMx
1 Replies

Featured Tech Videos