Moment get the HH and ss - javascript

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

Related

Extract hour and minute from date function

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

Timesheet hours difference in moment.js

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.

How can I get the correct output with Moment.js and "fromNow"?

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>

How to add time to time (minutes + minutes) in Javascript ? (Not to Date)

I don't finde anywhere how to add time to time, like adding 45 minutes to 45 minutes and having 1:30 (1 hour, 30 minutes).
I just find how to add time to actual Date.
Heres an example in PHP of what I'm looking for:
$seconds_toadd = 45;// VALUE TO GET FROM A TEXTBOX
$actual_value = '00:45'; //45 minutes, 0 hours is the actual value
$resultado = new DateTime($lectura_xml);
$resultado->add(new DateInterval('PT' . $seconds_toadd . 'S'));//This is how I add seconds in PHP
$stamp = $resultado->format('I:s');//Formatting result
echo $stamp;
Thank you.
Moment.js is a great library for date/time handling in JavaScript and better than the standard API and any homemade solution in many aspects.
Very simple but similar use case from their docs:
var a = moment.duration(1, 'd');
var b = moment.duration(2, 'd');
a.add(b).days(); // 3

get time different (minutes) in javascript

How do I calculate the difference in minutes given two strings. For example say I have
11:00
11:30
But of course the second string could be 12:11 so I can't subtract just the minutes.
first use javascript to convert the strings to time, then subtract, then convert back to strings
like this:
x = new Date("1/1/01 11:00")
y = new Date("1/1/01 11:30")
// now y-x has difference in milliseconds
// (y-x)/1000 is difference in seconds, etc
The data 1/1/01 is just being used as a dummy value, but the one thing you might have to worry about is are the times on different days, if so you will have to use 1/2/01 for the second time. Unless of course you always know the times are in the same day, but if they can cross "midnight" then you have to adjust for that.
You may want to use http://momentjs.com/ which will take care of the details for you.
When looking for getting metrics such as date , hour , minutes, seconds from the date difference, it's a lot easier to use basic notations as listed here
var x = new Date(new Date().getTime() + 11.5*60*60000); // adds 11 hours - 30 minutes
var y = new Date(new Date().getTime() + 11*60*60000); // adds 11 hours
alert(x.getMinutes() - y.getMinutes()); // gives the difference = 30
Here's an example : https://jsfiddle.net/DinoMyte/157knmgn/

Categories

Resources