How do you calculate difference in time (hours and minutes) between 2 two date/time fields?

Have trouble creating formula using FormCalc that will calculate difference in time (hours and minutes) from a Start Date/Time field and End Date/Time field. 
I am using to automatically calculate total time in hours and minutes only of an equipment outage based on a user entered start date and time and end date and time. 
For example a user enters start date/time of an equipment outage as 14-Oct-12 08:12 AM and then enters an end date/time of the outage of 15-Oct-12 01:48 PM.  I need a return that automatically calculates total time in hours and minutes of the equipment outage.
Thanks Chris

Hi,
In JavaScript you could do something like;
var DateTimeRegex = /(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d)/;
var d1 = DateTimeRegex.exec(DateTimeField1.rawValue);
if (d1 !== null)
    var fromDate = new Date(d1[1], d1[2]-1, d1[3], d1[4], d1[5]);
var d2 = DateTimeRegex.exec(DateTimeField2.rawValue);
if (d2 !== null)
    var toDate = new Date(d2[1], d2[2]-1, d2[3], d2[4], d2[5]);
const millisecondsPerMinute = 1000 * 60;
const millisecondsPerHour = millisecondsPerMinute * 60;
const millisecondsPerDay = millisecondsPerHour * 24;
var interval = toDate.getTime() - fromDate.getTime();
var days = Math.floor(interval / millisecondsPerDay );
interval = interval - (days * millisecondsPerDay );
var hours = Math.floor(interval / millisecondsPerHour );
interval = interval - (hours * millisecondsPerHour );
var minutes = Math.floor(interval / millisecondsPerMinute );
console.println(days + " days, " + hours + " hours, " + minutes + " minutes");
This assumes that the values in DateTimeField1 and DateTimeField2 are valid, which means the rawValue will be in a format like 2009-03-15T18:15
Regards
Bruce

Similar Messages

  • Calculate difference between two dates/times

    Hi all,
    Is there any function module to calculate difference between two dates/times which are in TIMESTAMPL format.
    I need to know how many millisconde(second,minutes, hours... )there is between these two times.
    Please, It is urgent
    Thank you all.
    Karim

    hi,
    try the following function
    CALL FUNCTION 'CCU_TIMESTAMP_DIFFERENCE'        
          EXPORTING                                  
               timestamp1 = timestamp1               
               timestamp2 = timestamp2               
          IMPORTING                                  
               difference = diff                     
          EXCEPTIONS                                 
               OTHERS     = 1. 
    the above function gives the difference in seconds...
    try the following  code to set the resolution to milliseconds..
    SET RUN TIME CLOCK RESOLUTION LOW
    check the thread for details:
    SET RUN TIME CLOCK RESOLUTION?
    all the best!!!
    Regards,
    Aparna

  • How to count the number of Fridays and Saturdays between two dates

    Hi every one ... If we want to count the number of Fridays and Saturdays between two dates, how would we do that ? !
    Dates are ( 11-Feb-2010) to (19-May-2010)
    how to do it in SQL
    Edited by: khalidoracleit on Jul 28, 2010 5:51 AM

    some nice coding here, I'm still amazed with what some people can do with "connect by". But I agree with some statements here that this can take "time", and to be honest, it's funny to see it working, but if you do not have a computer, just a calendar and some paper, would you go for "counting" so there must be a better solution?
    The best working math in here is done by Aketi Jyuuzou, who writes so good English that I wonder why he still insists that he doesn't ;-)
    Anyhow I "translated" that code to English, and I really like that math. Math is math and data is data.
    ALTER SESSION SET NLS_DATE_LANGUAGE='ENGLISH';
    WITH my_dates AS (
    SELECT to_date('20100211','yyyymmdd') start_date,to_date('20100519','yyyymmdd') end_date FROM DUAL
    UNION ALL
    SELECT to_date('20100211','yyyymmdd') start_date,to_date('20100214','yyyymmdd') end_date FROM DUAL
    UNION ALL
    SELECT to_date('20100211','yyyymmdd') start_date,to_date('20100213','yyyymmdd') end_date FROM DUAL
    UNION ALL
    SELECT to_date('20100211','yyyymmdd') start_date,to_date('20100212','yyyymmdd') end_date FROM DUAL
    SELECT to_char(start_date,'DD.MM.YYYY') start_date,to_char(end_date,'DD.MM.YYYY') end_date,
           to_char(start_date,'DAY') start_weekday,to_char(end_date,'DAY') end_weekday,
           end_date-start_date day_difference,
           (next_day(end_date,'FRIDAY')-7
           -next_day(start_date -1,'FRIDAY'))/7+1
           +(next_day(end_date,'SATURDAY')-7
           -next_day(start_date -1,'SATURDAY'))/7+1 as count_of_fr_and_sat
    FROM my_dates;
    START_DATE END_DATE   START_WEEKDAY                        END_WEEKDAY                          DAY_DIFFERENCE         COUNT_OF_FR_AND_SAT   
    11.02.2010 19.05.2010 THURSDAY                             WEDNESDAY                            97                     28                    
    11.02.2010 14.02.2010 THURSDAY                             SUNDAY                               3                      2                     
    11.02.2010 13.02.2010 THURSDAY                             SATURDAY                             2                      2                     
    11.02.2010 12.02.2010 THURSDAY                             FRIDAY                               1                      1                      -- andy

  • Calculate the difference between two dates times in infopath form 2013

    Hi,
    I have an infopath 2013 form that contains three fields:
    2 date time and the 3rd contains the difference between the two in hours
    how I can make the difference between the two so that the display will be like this:
    Date Time1           08/21/2014           22:00 
    Date Time2           08/22/2014           1:00
    Diff Field                                             3:00

    Hi,
    Please refer to the following article which matches your requirement exactly.
    Calculate the difference between two date picker controls in InfoPath using rules and formulas - no code!
    Please mark it answered, if your problem resolved.

  • How to calculate  number of sundays and saturdays between two Dates

    friends i want to calculate how many Sundays come in two Dates
    i have tried following code which is hard coded i have to impliment method which can give me number of Sundays between two Dates
    please help me
    import java.util.Date;
         import java.text.DateFormat;
         import java.text.SimpleDateFormat;
         import java.util.Calendar ;
         import java.util.GregorianCalendar;
    public class DateDiffCalculator     {
         private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MMM-dd");
    public DateDiffCalculator()     {
         public static Date getDate (String date) throws Exception {
    //log.debug(" "+date);
              return SDF.parse(date);
    public static Date getDate (Date date) throws Exception {
    // log.debug("date is "+date);
              return getDate(SDF.format(date));
    public static long getDiffInDays(Date d1,Date d2)     {
         boolean isdiffGreaterThanYear=false;
         long diffInMilliSeconds=d1.getTime()-d2.getTime();
         return diffInMilliSeconds/(1000*60*60*24);
    public static int getYear(String date)     {
              //String[] day=     {Sun,Mon,Tue,Wed,Thu,Fri,Sat};
              Integer     year=new     Integer(date.substring(0,4));
         return year.intValue();
    public static int getMonth(String date)     {
              //String date.substring(5,7);
              System.out.println(" "+date.substring(5,8));
              String     m= date.substring(5,8);
              int month=0;
              if(m.equalsIgnoreCase("Jan"))     {
              month=1;
              if(m.equalsIgnoreCase("Feb"))     {
              month=2;
              if(m.equalsIgnoreCase("Mar"))     {
              month=3;
              if(m.equalsIgnoreCase("Apr"))     {
              month=4;
              if(m.equalsIgnoreCase("May"))     {
              month=5;
              if(m.equalsIgnoreCase("Jun"))     {
              month=6;
              if(m.equalsIgnoreCase("Jul"))     {
              month=7;
              if(m.equalsIgnoreCase("Aug"))     {
              month=8;
              if(m.equalsIgnoreCase("Sep"))     {
              month=9;
              if(m.equalsIgnoreCase("Oct"))     {
              month=10;
              if(m.equalsIgnoreCase("Nov"))     {
              month=11;
              if(m.equalsIgnoreCase("Dec"))     {
              month=12;
              return month;
         public static int getDay(String date)     {
              Integer     day=new     Integer(date.substring(9,11));
         return day.intValue();
    public static int getNumberofSundays(String d1,String d2) throws Exception     {
              //d1 is leave start date d2 is leave end date
              // get object in Date form
                   Date date1=getDate(d1);
                   Date date2=getDate(d2);
              // now get calender objects from it
              GregorianCalendar c1= new GregorianCalendar(getYear(d1),getMonth(d1),getDay(d1));
              GregorianCalendar c2= new GregorianCalendar(getYear(d2),getMonth(d2),getDay(d2));
              // get period
              long leavePeriod = getDiffInDays(date1,date2);
         return 12; // it should return number of sundays but we type 12 to perform compilation
    public static void main(String[] arg)throws Exception     {
    System.out.println(" "+getNumberofSundays("2005-Oct-07","2006-Mar-01"));
    }

    thanks now i have modified the get Month Code
    as follows
    public static int getMonth(String date)     {
              //String date.substring(5,7);
              System.out.println(" "+date.substring(5,8));
              String     m= date.substring(5,8);
              int month=0;
              if(m.equalsIgnoreCase("Jan"))     {
              month=0;
              if(m.equalsIgnoreCase("Feb"))     {
              month=1;
              if(m.equalsIgnoreCase("Mar"))     {
              month=2;
              if(m.equalsIgnoreCase("Apr"))     {
              month=3;
              if(m.equalsIgnoreCase("May"))     {
              month=4;
              if(m.equalsIgnoreCase("Jun"))     {
              month=5;
              if(m.equalsIgnoreCase("Jul"))     {
              month=6;
              if(m.equalsIgnoreCase("Aug"))     {
              month=7;
              if(m.equalsIgnoreCase("Sep"))     {
              month=8;
              if(m.equalsIgnoreCase("Oct"))     {
              month=9;
              if(m.equalsIgnoreCase("Nov"))     {
              month=10;
              if(m.equalsIgnoreCase("Dec"))     {
              month=11;
              return month;
    but question remains same how to calculate number of Sundays Between 2 Dates

  • Date difference function that returns minutes between two dates and excludes weekends and holidays

    Is there a way to get this to work as a function? 
    Currently returns error "Select statements included within a function cannot return data to a client"
    CREATE FUNCTION [dbo].[WorkDays](@DateFrom datetime,@DateTo datetime)
    RETURNS int
    AS
    BEGIN
    --Working time
    DECLARE @WTFrom TIME = '8:00AM';
    DECLARE @WTTo TIME = '5:00PM';
    DECLARE @minCount BIGINT
    --Date ranges
    IF (DATEDIFF(HOUR, @DateFrom, @DateTo) > 12)
    BEGIN
    WITH CTE AS
    SELECT @DateFrom AS DateVal
    UNION ALL
    SELECT DATEADD(HOUR, 1, DateVal)
    FROM CTE
    WHERE DateVal < DATEADD(HOUR, -1,@DateTo)
    SELECT DATEDIFF(minute, MIN(CTE.DateVal), MAX(CTE.DateVal))
    FROM CTE
    WHERE (CAST(CTE.DateVal AS time) > @WTFrom AND CAST(CTE.DateVal AS time) < @WTTo) AND DATEPART(dw, CTE.DateVal) NOT IN (1, 7) AND NOT EXISTS (SELECT * FROM Holiday AS H WHERE H.holiday = CTE.DateVal)
    OPTION (MAXRECURSION 0);
    END;
    ELSE
    BEGIN
    WITH CTE AS
    SELECT @DateFrom AS DateVal
    UNION ALL
    SELECT DATEADD(MINUTE, 1, DateVal)
    FROM CTE
    WHERE DateVal < DATEADD(MINUTE, -1,@DateTo)
    SELECT DATEDIFF(minute, MIN(CTE.DateVal), MAX(CTE.DateVal))
    FROM CTE
    WHERE (CAST(CTE.DateVal AS time) > @WTFrom AND CAST(CTE.DateVal AS time) < @WTTo) AND DATEPART(dw, CTE.DateVal) NOT IN (1, 7) AND NOT EXISTS (SELECT * FROM Holiday AS H WHERE H.holiday = CTE.DateVal)
    OPTION (MAXRECURSION 0);
    END;
    END
    Thanks for your help.

    Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules (you do not). Temporal
    data should use ISO-8601 formats (you do not!). Code should be in Standard SQL as much as possible and not local dialect. 
    This is minimal polite behavior on SQL forums. 
    We hate functions in SQL. This is a declarative language and you are using it like 1950's FORTRAN. We hate local variables (more FORTRAN!)
     The name of a function has to be either a known, common name, like “sine”, “cosine” etc. Or it is “<verb>_<object>”; you think a noun is a verb! Do you really need BIGINT? Why did you invite garbage data with it? Why do you think that SQL
    uses AM/PM? Have you never seen the TIME data type? 
    Think about “date_val” as a data element name. A date is a unit of temporal measurement on a calendar scale. This would be a “<something>_date” in a valid schema. 
    >> Is there a way to get this to work as a function? <<
    Probably, but why do it wrong?
    Build a calendar table with one column for the calendar data and other columns to show whatever your business needs in the way of temporal information. Do not try to calculate holidays in SQL -- Easter alone requires too much math.
    The julian_business_nbr is how SQL people do this. Here is the skeleton. 
    CREATE TABLE Calendar
    (cal_date DATE NOT NULL PRIMARY KEY, 
     julian_business_nbr INTEGER NOT NULL, 
    Here is how it works:
    INSERT INTO Calendar 
    VALUES ('2007-04-05', 42), 
     ('2007-04-06', 43), -- Good Friday 
     ('2007-04-07', 43), 
     ('2007-04-08', 43), -- Easter Sunday 
     ('2007-04-09', 44), 
     ('2007-04-10', 45); --Tuesday
    To compute the business days from Thursday of this sample week to next Tuesday:
    SELECT (C2.julian_business_nbr - C1.julian_business_nbr)
      FROM Calendar AS C1, Calendar AS C2
     WHERE C1.cal_date = '2007-04-05',
       AND C2.cal_date = '2007-04-10'; 
    See how simple it can be when you stop trying to write FORTRAN and think in sets? 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Calculation between two date time

    hi,
    This is my table structure :
    In_time Date;
    Out_time Date;
    Duration Number;
    user enter the In_time and Out time data is 12:30 like this ( HH24:mi format).
    for Example
    In_time Out_time duration
    12.30 2.00 1:30
    I want to store the difference b/w In_time and Out_time to be insert in the duration column;

    :out_time - :in_time is duration in days, if both items are of type date or datetime.
    but why are you storing redundant data?
    in_time and duration OR in_time and out_time is enough ...

  • How to get a list of material numbers(IDH) generated between two dates

    Hi
    I want to get a list of mateial numbers which are uploaded in last one year.Need help.

    Look at classes Calendar and SimpleDateFormat.
    And get your abstraction straight: you don't have two dates. You have two Strings that represent a date. To use them, you have to convert them to Date objects first with SDF.

  • When using a new pc, how do you download all of your music and playlists at the same time?

    I bought a new pc, and I would like all of my itunes content on here. I seem to be able to only download one song at a time. How can I get my entire library on my new pc

    Hello beckyinindiana,
    Thanks for using Apple Support Communities.
    For more information on this, take a look at:
    iTunes: How to move your music to a new computer
    http://support.apple.com/kb/ht4527
    Best of luck,
    Mario

  • HT3354 amount of hours and minutes between to sets of time?

    Two columns have a time in them (ex. B2 has 7:45am and C2 has 4:15pm). I need E2 to show me that equals 8.5 hours.  What is the formula?

    A1=24*(TIMEVALUE(C1)- TIMEVALUE(B1))

  • How do you knock off bank holidays, saturdays and sundays for pay dates

    Hi, there,
    For simplicity, lets not go a far as bank holidays, at least I want to be able to run a job not using the DBMS.jobs package but on a trigger.
    I want payments to go through at least on the 28th day of every month but it might fall on a weekend.
    1* SELECT TO_CHAR(TRUNC(SYSDATE, 'MM')+27) FROM DUAL
    SQL> /
    TO_CHAR(T
    28-APR-06
    Do you think it can be done to push payment to the next working day if it falls on a weekend.
    What do you think is best practise.
    Contributions will be highly appreciated.
    This is for learning purposes
    cube60.

    Hi Jameel and others,
    I am trying to insert a paymentdate in a monthly_payment table, but would like it to fall on a work day and not a weekend.
    Jameel's last post based on a CASE select statement was very useful in helping me out. I have been trying to transform that CASE statement into a function or a procedure. This function or procedure would be fired by a trigger when the date columns need to be filled when updating other columns in the same table using a call procedure.
    More or less, this function is meant to fill in just a column in a row or rows of data when the other columns are about to be updated using another procedure.
    Am i right with using a function in this situation?
    see below for my errors:
    SQL> create or replace function paymentdate
    2 is
    3 return v_date date;
    4 Begin
    5
    6 select to_char(trunc(sysdate,'MM')+27,'Day') into v_date from dual;
    7
    8 if (v_date) ='sat' then
    9 insert into contract_staff_pay (paymentdate) values (v_date + 2);
    10 end if;
    11
    12 if (v_date) ='sun' then
    13 insert into contract_staff_pay (paymentdate) values (v_date + 1);
    14 else
    15 insert into contract_staff_pay (paymentdate) values (v_date);
    16 end if;
    17 end;
    18 /
    Warning: Function created with compilation errors.
    SQL> show err;
    Errors for FUNCTION PAYMENTDATE:
    LINE/COL ERROR
    2/1 PLS-00103: Encountered the symbol "IS" when expecting one of the
    following:
    ( return compress compiled wrapped
    Many thanks in advance.
    cube60

  • How to set just hour and minute to a Calendar object and do comparsion

    hi there
    can anyone show me how to just set the time : hour and minute to a calendar obj and do comparion? for instance, compare mid night with 7:24pm, how do i create objects to do it? thanks

    Or I'll just post them here to save the trouble...
        Calendar xmas = new GregorianCalendar(1998, Calendar.DECEMBER, 25);
        Calendar newyears = new GregorianCalendar(1999, Calendar.JANUARY, 1);
        // Determine which is earlier
        boolean b = xmas.after(newyears);            // false
        b = xmas.before(newyears);                   // true
        // Get difference in milliseconds
        long diffMillis = newyears.getTimeInMillis()-xmas.getTimeInMillis();
        // Get difference in seconds
        long diffSecs = diffMillis/(1000);           // 604800
        // Get difference in minutes
        long diffMins = diffMillis/(60*1000);        // 10080
        // Get difference in hours
        long diffHours = diffMillis/(60*60*1000);    // 168
        // Get difference in days
        long diffDays = diffMillis/(24*60*60*1000);  // 7

  • How to calculate the hour difference between two dates?

    hi all,
    how to calculate the hour difference between two dates?
    eg i trying this...
    ((TO_DATE(TO_CHAR(GRNi.reference_date_4,'hh24:mi'),'hh24:mi') -
    TO_DATE(TO_CHAR(NVL(GRNi.reference_date_3,SYSDATE),'hh24:mi'),'hh24:mi'))*24)*60 Act_Hr
    Reg.
    AAK

    Hi
    To break the diff between 2 dates into days, hours, minutes, sec -- you can use the following:
    select to_char( created, 'dd-mon-yyyy hh24:mi:ss' ),
    trunc( sysdate-created ) "Dy",
    trunc( mod( (sysdate-created)*24, 24 ) ) "Hr",
    trunc( mod( (sysdate-created)*24*60, 60 ) ) "Mi",
    trunc( mod( (sysdate-created)*24*60*60, 60 ) ) "Sec",
    to_char( sysdate, 'dd-mon-yyyy hh24:mi:ss' ),
    sysdate-created "Tdy",
    (sysdate-created)*24 "Thr",
    (sysdate-created)*24*60 "Tmi",
    (sysdate-created)*24*60*60 "Tsec"
    from all_users
    where rownum < 50
    HTH
    RangaReddy

  • Difference between two dates and time in hours

    Hi,
    I have fields contains start date, start time, end date, end time.
    How do I calculate the number of hours since start date, start time and end date, end time
    Start date : T_DATE1
    Start time : T_TIME1
    End Date : T_DATE2
    End Time : T_TIME2.
    Please help
    Moderator Message: Date and Time questions are not allowed in this forum. The reason being they have been asked and answered many times here. Please search for relevant information here.
    Edited by: kishan P on Dec 16, 2011 12:02 PM

    Hi,
    Please find the FM - DELTA_TIME_DAY_HOUR,
    this will give you the time in minutes, hence you can convert it to hours.
    Please note the below links;
    Moderator Message: Link-farm removed. Please dont do that again.
    Hope you will search SDN next time, before posting.
    And too hope that this will help you
    Thanks & Regards
    Manu S
    Edited by: kishan P on Dec 16, 2011 12:03 PM

  • How do I get a time value in days, hours and minutes returned to a cell from a calculation of distance divided by speed?

    How do I get a time value in days, hours and minutes returned to a cell from a calculation of distance divided by speed?

    Simon,
    you can use the duration function:
    B4=DURATION(0,0,B1/B2)
    you can further, format the cell as a duration like this using the cell inspector:

Maybe you are looking for