How to make time difference in custom script?

i tried this code but it doesn’t work

frappe.ui.form.on("OT Details", {
   to_time:function(frm, cdt, cdn){
   var d = locals[cdt][cdn];
   var f = locals[cdt][cdn];
   var hr= 0;
   hr = frappe.utils.data.time_diff(d.from_time, d.to_time);   
   frappe.model.set_value(f.doctype, f.name, "hours", hr);
 },

		var start = frm.doc.start_time.split(":");
		var end = frm.doc.end_time.split(":");
		var date1 = new Date(2000, 0, 1,  start[0], start[1]); 
		var date2 = new Date(2000, 0, 1, end[0], end[1]); 

		if (date2 < date1) {
			date2.setDate(date2.getDate() + 1);
		}

		var diff = date2 - date1;
		var msec = diff;
		var hh = Math.floor(msec / 1000 / 60 / 60);
		msec -= hh * 1000 * 60 * 60;
		var mm = Math.floor(msec / 1000 / 60);
		msec -= mm * 1000 * 60;
		var ss = Math.floor(msec / 1000);
		msec -= ss * 1000;
		
		frm.set_value("total_time", hh+":"+mm+":"+ss);
frappe.ui.form.on("Test", {
to_time:function(frm, cdt, cdn){
var d = locals[cdt][cdn];
	var hours=minutes=seconds=total=0
	if(d.from_time && d.to_time)
	{
		var startTime=moment(d.from_time, "HH:mm:ss");
		var endTime=moment(d.to_time, "HH:mm:ss");
		var duration = moment.duration(endTime.diff(startTime));
		hours = parseInt(duration.asHours());
		minutes = parseInt(duration.asMinutes())%60;
		seconds=parseInt(duration.asSeconds())%60;
		console.log(hours + ' hour and '+ minutes+' minutes.' +seconds+'second');

	}
		frappe.model.set_value(cdt,cdn,"total",hours+":"+minutes+":"+seconds);
		frm.refresh_field("total");

},
from_time:function(frm, cdt, cdn){
var d = locals[cdt][cdn];
	var hours=minutes=seconds=total=0
	if(d.from_time && d.to_time)
	{
		var startTime=moment(d.from_time, "HH:mm:ss");
		var endTime=moment(d.to_time, "HH:mm:ss");
		var duration = moment.duration(endTime.diff(startTime));
		hours = parseInt(duration.asHours());
		minutes = parseInt(duration.asMinutes())%60;
		seconds=parseInt(duration.asSeconds())%60;
		console.log(hours + ' hour and '+ minutes+' minutes.' +seconds+'second');
		
	}
		frappe.model.set_value(cdt,cdn,"total",hours+":"+minutes+":"+seconds);
		frm.refresh_field("total");

}

})
1 Like