Convert a Time Value Expressed as a String to Minutes in JavaScript - javascript

I am trying to convert string values expressed in hours and minutes -- for example, the values I'm working with are strings like so: "1:30" or "00:45" -- into minutes in JavaScript. I've seen plenty of examples going the other way, but haven't found any solutions for this particular question, where you go from a string value in this "0.00" string format to minutes.

Use a Date() object and the getMinutes() function. Since you only care about a time, you'll need to initialize the object with a dummy date...
var time = "01:45";
var d = new Date("2000-01-01 " + time + ":00");
var minutes = d.getMinutes() + (d.getHours() * 60);
console.log(minutes.toString());

Related

How to convert Excel Hour Serial Number to the H:M format?

Inside of Excel file, I have an hour:minute time format, example of one value from that excel file is: "19:15"
After uploading that file to my application, it is being read as "0.8020833333333334".
I want to convert that value from column ("0.8020833333333334") to get hours and minutes.
Here's what I have accomplished so far:
const extractTime = new Date(Math.round((0.8020833333333334 - 25569) * 864e5));
The result is not what I expected.
How can I convert this number to get the hour as 19, and minutes as 15?
I've been "digging" around StackOverflow's questions about this, and my answer is based on this question's answers, as well as ECMA's date time. Mostly my answer is based on this answer.
In the comments you can see, that there will be problems if you're working with date-time values, based on this comment:
This anwer is wrong for 2 reasons: 1) the final Date constructor in
the return value will create the time as a local time - results will
differ depending on the client. 2) the solution does not take the 1900
leap year bug into account. I believe my solutions solves both issues. https://stackoverflow.com/a/57184486/12826055
And in case someone is working with date-time format, I would suggest using the answer which is linked inside of quotes, but in the case you only have TIME (19:30 -> 0.8020833333333334) and similar, it will be correct to use the code below.
Code:
var serial = 0.8020833333333334
var fractional_day = serial - Math.floor(serial) + 0.0000001;
var total_seconds = Math.floor(86400 * fractional_day);
var seconds = total_seconds % 60;
total_seconds -= seconds;
var hours = Math.floor(total_seconds / (60 * 60));
var minutes = Math.floor(total_seconds / 60) % 60;
console.log(hours)
console.log(minutes)
Outputs:
19
15

How to format MySQL timestamp using jquery

I read timestamp from MySQL db (is type timestamp).
Like this: 2017-04-01 15:34:31
I want to format this date using jquery and set up to some span element.
I am new in jquery and I don't know how to do it.
Thank you.
Try the DATE_FORMAT(date,format) function in MySQL. Something like:
DATE_FORMAT(NOW(),'%m-%d-%Y')
would give you 04-01-2017. Then wrap that in a <span>.
If you are using PHP then
strftime('%m-%d-%Y',$timestamp);
is an alternative. there are plenty of examples in Stack Overflow; Google will get you there.
If you would are receving the timestamp on the client side you can Convert a Unix timestamp to time in JavaScript
// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
To add the formatted text to a span you could use javascript or jQuery
// Javascript
document.querySelector("span").text(formattedTime);
// jQuery
$("span").text(formattedTime);
For more information regarding the Date object, please refer to MDN or the ECMAScript 5 specification.
Additionally:
If you must use jQuery instead of Javascript, consider a plugin
https://github.com/phstc/jquery-dateFormat
There is Javascript library https://momentjs.com/ for time
There is a great JS talk about time https://www.youtube.com/watch?v=2BdFg5JT9lg
Date(Date.parse(data.timestamp[i]))
This works assuming you are iterating through timestamps sent to the frontend from a Mysql query, which returns arrays. You could also write it like:
Date(Date.parse("2020-01-08 06:36:59"))

Add specified minutes to time using javascript

How we can add minutes to time, I want to add:
time = 21:36:13 and minutes 21:33
and want to get result 21:57:46
A JavaScript Date object stores time as the number of milliseconds since 1970/01/01 00:00:00 (in what should be UTC if the rest of your application is written properly). To add minutes and seconds, simply multiply te values to get the equivalent number of milliseconds, something like this: newDate = new Date(oldDate.getTime() + (((minutesToAdd * 60) + secondsToAdd) * 1000))
You should think about what you expect to happen during daylight saving time transitions. If the application is designed properly, the value in the Date object will be UTC, so the calculation above will always work correctly, but obviously the displayed value will be formatted as local time.
You may find a library such as Datejs useful.
What are you using to represent time? if you are using a native Date object, you can do something like this:
var addTime = function (baseDate, hours, minutes, seconds) {
return new Date(baseDate.getTime() + hours*3600000 + minutes*60000 + seconds*1000);
}
This is basically creating a new Date object adding a series of hours, minutes and seconds to the base Date provided (all of it in milliseconds). Here's the reference to work with Date objects.
You can use Date object with only taking interest in time. Here is your example:
function Foo()
{
time = new Date();
time.setHours(21);
time.setMinutes(36);
time.setSeconds(13);
time.setMinutes(time.getMinutes() + 21);
time.setSeconds(time.getSeconds() + 33);
alert(time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds());
}
Hope it helps :D

Convert exact date to time ago using jquery - What format for the date?

I have a static page which will specify a hardcoded exact date. If the use has javascript, I want to then convert this hardcoded exact date into a "time ago".
For example:
3 hours ago
My question is, in what format of date will javascript be able to most efficiently convert to the time ago?
10/10/13
10.10.13
10th October 2013
101013
I would look at this post: https://stackoverflow.com/a/3177838/2895307
In it he just uses a javascript Date() as the parameter to the "timeSince()" function. To create a javascript Date from your hardcoded string you can use this format:
var d1 = new Date("October 13, 1975 11:13:00")
definitely unix timestamp is the best format for all date and time calculations, you can convert the results to a more readable format later.
the calculation is simple, you start with the timestamp of an event in the past, for example:
var anHourAgo = Date.now() - 3600000;
then you substract that from the current timestamp and get the number of milliseconds that have passed since that event
Date.now() - anHourAgo
then you can pass that to any function that will convert those milliseconds to hours, minutes and seconds, here's an example that takes seconds and returns an array with that info, and another function that pads those numbers with zeros
var zeroPad = function(n){
return n.toString().replace(/^(\d)$/,'0$1');
};
var formatSecs = function(s){
var r = [
Math.floor(s / 3600),
Math.floor(s%3600 / 60),
Math.floor((s%3600)%60)
];
r.push(zeroPad(r[0])+':'+zeroPad(r[1])+':'+zeroPad(r[2]));
return r;
};
the formatSecs function expects seconds instead of millseconds, you should divide by 1000 and round that number, then pass that number to the function
Math.round(Date.now() - anHourAgo) / 1000
Finally here's a working example of all that code in action:
http://codepen.io/DavidVValdez/pen/axHGj
i hope this helps, cheers!
The easiest thing to do would be to use Date.getTime().
This will give you the number of milliseconds since the Unix epoch and will make the math very simple.
Date.getTime

JQuery datetime to milliseconds

I have a web application where I wish to send information to a database.
I have a datepicker, which lets the user select a date and formats the date as "YYYY-MM-DD". In addition to this, the users must also select a time using a timepicker which formats the time as "HH:MM". This gets concatenated into a DateTime string as "YYYY-MM-DD HH:MM".
I need to convert this into milliseconds for the datetime to be accepted as the correct format on the database (locale format of YYYY-MM-DD HH:MM:SS.mmm).
I have a tried a host of solutions found here and elsewhere to try and convert into milliseconds. Whenever I try to concat then convert I usually get a NaN error or "invalid Date" and I cannot simply add the converted milliseconds.
Is there any way of doing this in jQuery or JavaScript?
>> var datetime = new Date();
undefined
>> datetime.getTime();
1332613433314
Date.getTime() returns the number of milliseconds since 1970/01/01:
This should be handled server-side, though.
I managed to figure this one out myself. Thanks to those who answered. Its not an ideal solution, but it works.
var d = $("#date").val();
var dateParts = new Date((Number(d.split("-")[0])), (Number(d.split("-")[1]) - 1), (Number(d.split("-")[2])));
var dateis = dateParts.getTime();
var timeEnd = $("#endtime").val();
var time1 = ((Number(timeEnd.split(':')[0]) * 60 + Number(timeEnd.split(':')[1]) * 60) * 60) * 1000;
var timeStart = $("#starttime").val();
var time2 = ((Number(timeStart.split(':')[0]) * 60 + Number(timeStart.split(':')[1]) * 60) * 60) * 1000;
var dateTimeEnd = dateis + time1;
var dateTimeStart = dateis + time2;
What this basically does, is take a date from a datepicker, and a start and an endtime from a timepicker. The ajax accepts 2 datetimes, one for start, one for end. The above solution basically gets all the values from the input values, and converts it to milliseconds. It's not the best way of doing things but it is a quick fix.
I don't realise your actual question, but I've made a code that set the datepicker to a minimum selected day as today the code is as follows :
$("#datefield").datepicker({
dateFormat:"yy-mm-dd",
minDate:new Date(new Date().getTime())
});
The return value of the new Date().getTime() is the milliseconds from 1970/01/01 05:30 am (as my system)
Can you use the JavaScript Date object?
You could use it like so:
var d = new Date(yyyy, MM, dd, hh, mm, 0, 0).getTime();
You initialize the Date object and then use the getTime function to return the number of milliseconds since Jan. 1, 1970.
$("#datefield").datepicker("getDate").getTime(); will do the trick
I would do this on the server side and use the strtotime function to convert to a timestamp which will give you a number of seconds which if you really need milliseconds for some kind of script : 1 second = 1000 milliseconds.
If anything you could use jquery to validate that you'll be sending a valid date-time to the server side script before you do so.

Categories