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);
}
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(':');
Related
Check If date exceeds 24Hrs from start date in moment.
Ex:
My date string **"27-05-2021 10:26:29 PM"**. I want to check from this start date exceeds or not. I'm using moment.js
You can use moment js format and diff function.
let a = moment("27-05-2021 10:26:29 PM", "DD-MM-YYYY hh:mm:ss A");
let b = moment();//todays date in local time zone
console.log(a.diff(b, "hours"));
First of all you need to parse string to get a valid date.
If you will use moment(dateString) directly, invalid date will be the result:
const dateString = '27-05-2021 10:26:29 PM';
const startDate = moment(dateString); // invalid date
so:
// parse string using format string to get a valid date
const dateString = '27-05-2021 10:26:29 PM';
const startDate = moment(dateString, 'DD-MM-YYYY hh:mm:ss a');
// finally get the difference from other date in hours/minutes/years
const today = moment(); //to get todays date
const hoursDiff = today.diff(startDate, 'hours'); //diff in hours
const minutesDiff = today.diff(startDate, 'minutes'); //diff in minutes
You can use diff and duration
var x = moment('27-05-2021 10:26:29 PM', ['DD-MM-YYYY HH:NN:SS']);
var y = new moment()
var duration = moment.duration(x.diff(y)).as('hours');
console.log(duration);
I used this code to convert epoch to human readable date
var timestamp = 1293683278;
var date = new Date(timestamp*1000);
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
I need to change it to UTC+3 how can i do this ?
Thanks for your help
The Date constructor treats time values as UTC. Date objects only ever represent UTC time, the "local" values produced by toString methods use system settings to determine the offset to use, but that's only for the sake of producing a timestamp, it doesn't change the underlying Date or its time value.
If you want a specific offset, you can choose an appropriate IANA location such as Africa/Nairobi, which is +3 all year round, and produce a timestamp using toLocaleString or Intl.DateTimeFormat, e.g.
console.log(
new Date().toLocaleString('default',{timeZone:'Africa/Nairobi', timeZoneName:'short'})
);
Just curious - but couldn't you just append 3 hours onto your timestamp before formatting it with your existing code. I'm curious if there's some date/calendar subtlety where this wouldn't reliably work.
const THREE_HOURS_IN_MS = 3*60*60*1000;
var date = new Date(timestamp*1000 + THREE_HOURS_IN_MS);
// rest of your code stays unchanged
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
You can use moment.js utcOffset to achieve this easily:
const moment = require("moment");
const timestamp = 1619071948 * 1000;
console.log(moment(timestamp).utcOffset(180).format("YYYY-MM-DDThh:mm:ssZ"));
The offset provided is in minutes
https://momentjs.com/docs/#/manipulating/utc-offset/
I want to subtract lunch hours from datetime differece
How it can be achieved?
var StartTime = moment(theList[i].start_time, "YYYY-MM-DD HH:mm:ss"); //2020-04-01 08:00:00.0
var EndTime = moment(theList[i].end_time, "YYYY-MM-DD HH:mm:ss"); //2020-04-01 18:00:00.0
var Lunch = moment(theList[i].lunch_time, "HH:mm:ss"); //00:30:00
var lunchTimeMs= moment(Lunch,"HH:mm:ss");
var ms = moment(EndTime,"YYYY-MM-DD HH:mm:ss").diff(moment(StartTime,"YYYY-MM-DD HH:mm:ss"));
var d = moment.duration(ms);
ms = moment().subtract(lunchTimeMs); //This gives wrong result
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
console.log("Total time " + i + " row" + s);
He is using Moment JS.
As far as I understood, the problem is that he has only date with time to manipulate in format similar to: dd.mm.YYYY HH:ii:ss.
My recommendation was to transfer server response datetime to timestamp using JS. It's much easier to manipulate date and time differences if you are using a timestamp.
UPDATE
Adding here my "vision" of JS date management (my fiddle). Feel free to improve it!
const date2timestamp= function(str){
_tmp = str.split(" ");
if(_tmp){
date_arr = ( _tmp[1] ? _tmp[0].split("-") : null );
time_arr = ( _tmp[1] ? _tmp[1].split(":") : _tmp[0].split(":") );
if(!date_arr) {
const today = new Date();
_date = Date.UTC(today.getFullYear(), today.getMonth(), today.getDate(), time_arr[0], time_arr[1], time_arr[2]);
}
else {
_date = Date.UTC(date_arr[0], date_arr[1]-1, date_arr[2], time_arr[0], time_arr[1], time_arr[2]);
}
date_obj = new Date(_date);
return date_obj.getTime()/1000;
}
return false;
}
document.write(
date2timestamp("2020-04-20 08:00:00")+"<br/>",
date2timestamp("2020-04-20 17:00:00")+"<br/>",
date2timestamp("00:03:00")
);
And now you have timestamps. When you subtract, you know, that the 1min = 60sec, so the result is ((7*60)+30)*60 = date2timestamp("2020-04-20 17:00:00")-date2timestamp("2020-04-20 17:00:00")-(30*60)
MORE UPDATES
But, reading about the moment.js a bit, there is even easier way. Manual for subtract says:
moment().subtract(1, 'seconds');
that means, you have to actually transfer your Launch period into seconds and then add put it into the subtract: moment().subtract((30*60), 'seconds') or just add (for test) 'millisecond' as second part of subtract:
...
ms = moment().subtract(lunchTimeMs, 'milliseconds');
// or use that
ms = moment().subtract(lunchTimeMs/1000, 'seconds);
...
Try this:
var StartTime = moment(theList[i].start_time, "YYYY-MM-DD HH:mm:ss");
var EndTime = moment(theList[i].end_time, "YYYY-MM-DD HH:mm:ss");
var Lunch = moment(theList[i].lunch_time, "HH:mm:ss");
var ms = moment(EndTime,"YYYY-MM-DD HH:mm:ss").diff(moment(StartTime,"YYYY-MM-DD HH:mm:ss"));
moment(ms).subtract(Lunch);
i'm trying to calculate the hours difference between to times using javascript. But i keep get the results NaN in the console. I get the current time using javascript and the late time from the localstorage
var log_time = localStorage.getItem('login_time')
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var hour = currentDate.getHours(); // => 9
var minute= currentDate.getMinutes(); // => 30
var second= currentDate.getSeconds(); // => 51
console.log(log_time);
var today = day + "/" + month + "/" + year
var time = hour + ":" + minute + ":" + second
console.log(today+' '+time);
var date1 = (log_time);
var date2 = (today+' '+time);
var hours = Math.abs(date2 - date1) / 36e5;
console.log(hours.toFixed(2))
the time from the localstorage reads 15/7/2017 9:30:46
You need to change your date format little bit This may Help you and also parse those dates because those are stirng formate.
Working Fiddle
var log_time1 = '2017-07-15 09:30:46';//Examples of ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.
var log_time = new Date(log_time1)//string parsing date
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var hour = currentDate.getHours(); // => 9
var minute= currentDate.getMinutes(); // => 30
var second= currentDate.getSeconds(); // => 51
var today = year + "-" + month + "-" + day
var time = hour + ":" + minute + ":" + second
var date1 = (log_time);
var test_date2 = (today+' '+time);
var date2= new Date(test_date2);//string parsing date
var hours = Math.abs(date2 - date1) / 36e5;
alert(hours.toFixed(2))
localStorage will store stringified version of any object, you need to parse it. If you converted it to milliseconds then also you need to parse it to number, it can save only string
var earlierDate = new Date( localStorage.getItem('login_time'))
// or var earlierDate = parseInt(localStorage.getItem('login_time'))
var currentDate = new Date()
var diff = currentDate - earlierDate;
Then convert diff to hour/minutes/seconds with your logic
Im not shure what youre trying to do here:
date2 - date1
These are booth strings, you cannot substract them. However you might convert them to milliseconds since 1970 which you could then do Math on:
var log_time = localStorage.getItem('login_time').split(" ");
log_time[0]=log_time[0].split("/").reverse().map((el,i)=>i?("0"+el).slice(-2):el).join("-");//5/4/2017 => 2017-04-05
log_time[1]=("0"+log_time[1]).slice(-8);// 9:30:10 => 09:30:10
var difference= new Date() - new Date(log_time.join("T"));
var hours=Math.floor(difference/(1000*60*60 /* one hour in ms */));
You may overthink the stored format. Its quite complicated to parse it properly.
http://jsbin.com/fofowayata/edit?console
I'm trying to convert UTC time to local time, but the below code is not working. What's wrong in it?
var parsedStartDateTime =
new Date(moment.unix(parseInt(data['StartDateTime'].substr(6)) / 1000));
var startDateTimeMoment =
moment.tz(parsedStartDateTime, tzName);
var formatted_date =
startDateTimeMoment.format("MMM DD YYYY h:mm:ss A");
To format your date try this:
var d = new Date();
var formatD = d.toLocaleFormat("%d.%m.%Y %H:%M (%a)");
Reference: Javascript to convert UTC to local time
Try appending UTC to the string before converting it to a date then use toString() method of date.
Example:
var myDate = new Date('7/1/2014 5:22:55 PM UTC');
date.toString(); //this should give you local date and time
This code was taken from here
Here is my solution:
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);
var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
var date = convertUTCDateToLocalDate(new Date(date_string_you_received));
date.toLocaleString().replace(/GMT.*/g,"");