1

Is it possible to do the below c# logic in javascript or jquery, The code converts duration between two dates int hours,minutes and seconds.the duration 20/01/2017 00:00:00 to 20/01/2017 02:20:30 will be 26:20:30 This about converting to hh:mm:ss format hours can go beyond 24, if minutes are more than 59 it should add to hours and seconds more than 59 should add to hours.

public static string ToTimeFormat(bool includeSeconds = false)
{
    var startDate = DateTime.parse("20/01/2017 00:00:00";
    var endDate = DateTime.parse("20/01/2017 02:20:30");
    var ts = endDate - startDate;
    var totalDaysToHours = ts.Days * 24;

    return string.Format("{0}:{1}", (ts.Hours + totalDaysToHours).ToString("0"), 
                                     ts.Minutes.ToString("D2")) 
                                     + (includeSeconds ? ":" + ts.Seconds.ToString("D2") : string.Empty);
}
Morteza Asadi
  • 1,819
  • 2
  • 22
  • 39
Shijith MC
  • 129
  • 3
  • 13
  • Get the ticks from both dates then do the subtraction. The ticks can be converted to any unit you choose (days, minutes, seconds). http://stackoverflow.com/questions/3224834/get-difference-between-2-dates-in-javascript – Jasen Jan 21 '17 at 03:12
  • Possible duplicate of [Get difference between 2 dates in javascript?](http://stackoverflow.com/questions/3224834/get-difference-between-2-dates-in-javascript) – Jasen Jan 21 '17 at 03:13
  • This not duplicate, This is to convert date into different format. – Shijith MC Jan 21 '17 at 03:23

1 Answers1

2

You can use moment.js from here moment.min.js and below is the code

var startDate  = "01/02/2016 00:00:00"; //MM/DD/YYYY HH:MM:SS format
var endDate = "01/03/2016 01:30:30"; //MM/DD/YYYY HH:MM:SS format
var diff = moment.duration(moment(endDate).diff(moment(startDate)));
var formatedData=[diff.asHours().toFixed(0), diff.minutes(), diff.seconds()].join(':');

so your output will be like

26:30:30

UPDATE

var startDate  = "01/02/2016 00:00:00".split(/\//);
startDate= [ startDate[1], startDate[0], startDate[2] ].join('/'); // DD/MM/YYYY to MM/DD/YYYY
var endDate = "01/03/2016 01:30:30".split(/\//);
endDate = [ endDate[1], endDate[0], endDate[2] ].join('/'); // DD/MM/YYYY to MM/DD/YYYY
var diff = moment.duration(moment(endDate).diff(moment(startDate)));
var formatedData=[diff.asHours().toFixed(0), diff.minutes(),diff.seconds()].join(':');
Pranav Patel
  • 1,541
  • 14
  • 28
  • How can I convert date to MM/DD/YYYY HH:MM:SS 'var formattedStartdt = moment(new Date(txtStartDate.value)).format("MM/DD/YYYY HH:mm:ss"); var formattedEnddt = moment(new Date(txtEndDate.value)).format("MM/DD/YYYY HH:mm:ss"); var diff = moment.duration(moment(formattedEnddt).diff(moment(formattedStartdt)));' – Shijith MC Jan 21 '17 at 09:29