I have a string '08:30-16:30' describing working hours.
I also have the time someone has worked, in HH:mm format,eg.09:15
What is the easiest-fastest way to convert them in dates and find the difference in HH:mm format ?
Should i use Moment.js?
Also,i need the difference in minutes or seconds so that i can do comparisons with that.
I would be grateful if you could give me some examples.
For finding the difference between the working hours, you could make use of MomentJS.
Example:
var working_hours = '08:30-16:30';
var hours_arr = working_hours.split('-'); // Gives an array with ['08:30', '16:30']
var start = moment(hours_arr[0], "HH:mm");
var end = moment(hours_arr[1], "HH:mm");
var duration = moment.duration(end.diff(start));
var minutes = parseInt(duration.asMinutes());
The minutes variable would contain the difference in minutes.
Related
I want to pass the time variable extracted from the database as a Date function in jQuery and want to extract hours and minutes from it and want to store it in a javascript variable.
var time="<?php echo $row['time']; ?>";
var time=new Date(time);
var hrs=time.getHours();
var min=time.getMinutes();
Please find if there is any error in this code.
Without more knowledge I can't really give you an answer.
But its likely that you're expecting a Date Object, when in reality your DB is returning something else.
(Maybe a string?, a number?)
Make sure what type of data is exactly storen in your "time" variable. Would be my suggestion because I dont see errors in the code. Must be the logic
Really hope this helped but more insight into what your DB is doing would help getting a clear answer :)
Good Luck !
You could find answers for this all over Stackoverflow or read the docs on the date object.
However, here is an answer you might like
var myMinutes = 1; // This represent 1 minute subtraction
var myHours = 60; // This represent 60 minutes subtraction which is 1 hour
var dateMSubObject= new Date(oldDateObject.getTime() - myMinutes*60000); //Substracting your minutes variable
var dateHSubObject= new Date(oldDateObject.getTime() - myHours*60000); //Substracting your hours variable
To make it more managable you could do hours like this aswell for etc 24 hours
var myHours = 60*24; // This represent 24 hours subtraction
You could also make the above code a function which wil take paramters like units, type and from that return your desired result
The 60000 part is milliseconds and represents 1 minute.
And welcome to StackOverflow, if you take some time exploring the website you will quickly be able to find the most common questions usually followed by great answers :)
This did it for me:
let jsdate = new Date(unixtimestamp+1000);
example in use:
let a = new Date();
console.log("a ="+a)
let stamp = a.getTime()
console.log("stamp ="+stamp) // timestamp
let newTimeObj = new Date(stamp*1000)
console.log("newTimeObj :::::::"+newTimeObj)
OUTPUT::::
You need to convert the UNIX Timestamp(in seconds) which is coming from your PHP code to milliseconds, and then pass it as a parameter to a Date object.
Consider the below example in JavaScript:
//UNIX Timestamp from your PHP code
let timeInUNIXTimeStamp = "1581653281";
// Create a new JavaScript Date object based on the timestamp
// Multiplied by 1000 to convert it into milliseconds, from seconds, as Date object works in milliseconds
var date = new Date(timeInUNIXTimeStamp * 1000);
// Get Hours part from the timestamp
var hours = date.getHours();
// Get Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Will display time in H:M format
var timeInHMSFormat = hours + ':' + minutes.substr(-2);
console.log(timeInHMSFormat);
You can same achieve in PHP also, there you need to convert UNIX Timestamp to H:M format, using the date() function, where the first parameter will the format you wanted and the second will be your UNIX Timestamp.
Example: date("h:i", 1581653281);
Where h is hours, in 12-hours format
i is minutes
Read move about PHP's data() function Date function in php
Consider PHP the code below, inside your JavaScript:
var time="<?php echo date('h:i', $row['time']); ?>";
//Now Split the above string into array
var timeArray = time.split(":");
var hours = timeArray[0];
var minutes = timeArray[1];
For more detail see this answer Convert UNIX Timestamp
I got the date in ISOFormats and time in 12hrs format. i need to combine togeather and get the output in ISOFormat using javascript. Im doing this in reactJs so using external libraries is fine
date = "2019-02-19T00:00:00.000Z"
startTime = "04.42PM"
outputDateTime = "2019-02-19T11:12:37.680Z"
Have a look at momentjs parse function.
Use it to convert the dates to moment objects and directly add them using the add function.
Example here
If you go pure vanilla I think this is fairly simple (AFAIK you only need hours and minutes and the zone is always fixed, if not, upgrade).
var yourDate = "2019-02-19T00:00:00.000Z";
var yourTime = "04.42PM"
var dat = yourDate.split("T")[0];
var minutes = yourTime.split(".")[1].slice(0,2);
var isPm = yourTime.split(".")[1].slice(2) === "PM";
var hours = isPm ? parseInt(yourTime.split(".")[0]) + 12 : yourTime.split(".")[0];
var date = new Date(dat+ "T" +hours+":"+minutes+":00Z");
Basically, I decomposed the input strings into interesting parts, compensated for PM if needed and put them back together :)
For the below program, the run date is 26/10/2017 and the variable deadline=29/10/2017.
I am using moment.js:
var deadline = '29/10/2017'
var days = moment(deadline, "DD/MM/YYYY").fromNow();
console.log(days)
<script src="https://momentjs.com/downloads/moment-with-locales.min.js"></script>
My output is in 2 days but actually I think the right answer is in 3 days
I think it is because fromNowis also calulating with the hours, so my question is, how can I reset this, so that I get the correct output?
You can use .endOf('day') on your deadline momentjs instance and you'll get 3 days.
You can also use a timestamp on top of your date such as 23:59 to get the same functionality.
var deadline = '29/10/2017'
var days = moment(deadline, "DD/MM/YYYY").endOf('day').fromNow();
// Change the time to 23:59:59 ^^^^^^^^^^^^^
console.log(days)
<script src="https://momentjs.com/downloads/moment-with-locales.min.js"></script>
Rather than using fromNow you can use from. With this, you can reset today's date to midnight and compare it against that instead:
var deadline = '29/10/2017',
now = new Date().setHours(0,0,0,0),
days = moment(deadline, "DD/MM/YYYY").from(now);
console.log(days)
<script src="https://momentjs.com/downloads/moment-with-locales.min.js"></script>
var end, moment, timeFormat;
moment = require('moment');
end = moment.utc('2016-11-29T23:59:59.999');
console.dir(end.format());
timeFormat = 'YYYY-MM-DDThh:mm:ss.SSS';
console.dir(end.format(timeFormat));
Output:
'2016-11-29T23:59:59Z'
'2016-11-29T11:59:59.999'
What I really need:
'2016-11-29T23:59:59.999'
Why is there a 12 hour difference between those 2 outputs? I could just add 12 hours to it, but that is hacky. I don't understand why moment is suddenly subtracting 12 hours from my date as soon as I give it a format. Seems unlikely this is a bug; more likely me misunderstanding what Moment is doing.
My timezone is GMT+8.
Because you are using hh (01-12) instead of HH (00-23); see the Moment.js format() docs.
Here is a working example:
var end, wrongTimeFormat, timeFormat;
end = moment.utc('2016-11-29T23:59:59.999');
console.dir(end.format());
wrongTimeFormat = 'YYYY-MM-DDThh:mm:ss.SSS';
timeFormat = 'YYYY-MM-DDTHH:mm:ss.SSS';
console.dir(end.format(wrongTimeFormat));
console.dir(end.format(timeFormat));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.0/moment.min.js"></script>
According to the Moment.js docs, lowercase hh will produce hours in the 01-12 range, which are meant to be used in conjunction with am/pm. You need capital HH (00-23, "military time"), as in
timeFormat = 'YYYY-MM-DDTHH:mm:ss.SSS'
use uppercase HH
timeFormat = 'YYYY-MM-DDTHH:mm:ss.SSS';
I am using moment.js. I have a variable that moment converts in to HH:ss format:
var mins, hours, time;
time = moment(selectedTime).format("HH:mm");
Which returns something like: 14:43 for example.
How can i get:
var hours to equal 14
var mins to equal 43
I have tried:
var mins, hours, time;
time = moment(selectedTime).format("HH:mm");
hours = moment(time).get('hour');
Which then hours returns NaN
var hours = moment(selectedTime).hours();
var mins = moment(selectedTime).minutes();
see http://momentjs.com/docs/#/durations/minutes/
The Solution that NimS has provided should work perfectly and suits your case very well. However if you simply need to display the values you can use the moment().format(XXX) method as you were previously and use the appropriate tokens from the documentation
For example
var mins, hours, time;
time = moment(selectedTime).format("HH:mm");
hours = moment(time).format('HH');
mins = moment(time).format('mm');
Take a look at the above example and you can format the time in any way you choose