jonthornton timepicker : How to get hours and minues - javascript

I'm using the jonthornton/jquery-timepicker and could not find the hours and minutes selected.
All I could find was a string output of the form '10:30pm'.
Can the hours and minutes be accessed directly from the control?
I imagined you would be able to do this but could not find it.
The best I've been able to do is what follows, anyone got anything better?
$('#StartTime').on('change', function (timeControl) {
var hoursString;
if (timeControl.target.value.indexOf("am") >= 0) {
hoursString = timeControl.target.value.replace("am", ":00 AM");
}
else {
hoursString = timeControl.target.value.replace("pm", ":00 PM");
}
var oneDate = new Date(Date.parse("2000-01-01 " + hoursString));
var minutes = oneDate.getMinutes();
var hours = oneDate.getHours();
console.log("Hours : " + hours + " | Minutes : " + minutes);
});

The long-standing answer would be Moment.js but it is now considered a legacy project in maintenance mode and not recommended for new projects. There are recommendations on their website for replacements, but bringing in a new dependency for this may be overkill.
The value coming in seems to follow a format which we can rely on to make parsing easy.
Format: H:MMxx
Key:
H = hour, 1-2 characters
MM = minutes, always 2 characters
xx = am or pm, always 2 characters
var timeArray = timeControl.split(':');
var meridiem = timeArray[1].substring(2, 4);
var hours = parseInt(timeArray[0]) + (meridiem === 'pm' ? 12 : 0);
var minutes = parseInt(timeArray[1].substring(0, 2));
var seconds = 0;
// Local time zone, read more: https://stackoverflow.com/a/29297375/5988852
var date = new Date();
date.setHours(hours, minutes, seconds);
// If you want UTC instead
utc = Date.UTC(
date.getUTCFullYear(),
date.getUTCMonth(),
date.getUTCDate(),
hours,
minutes,
seconds
);
var date = new Date(utc);

Related

Put clock forward by one hour [duplicate]

It amazes me that JavaScript's Date object does not implement an add function of any kind.
I simply want a function that can do this:
var now = Date.now();
var fourHoursLater = now.addHours(4);
function Date.prototype.addHours(h) {
// How do I implement this?
}
I would simply like some pointers in a direction.
Do I need to do string parsing?
Can I use setTime?
How about milliseconds?
Like this:
new Date(milliseconds + 4*3600*1000 /* 4 hours in ms */)?
This seems really hackish though - and does it even work?
JavaScript itself has terrible Date/Time API's. Nonetheless, you can do this in pure JavaScript:
Date.prototype.addHours = function(h) {
this.setTime(this.getTime() + (h*60*60*1000));
return this;
}
Date.prototype.addHours= function(h){
this.setHours(this.getHours()+h);
return this;
}
Test:
alert(new Date().addHours(4));
The below code will add 4 hours to a date (example, today's date):
var today = new Date();
today.setHours(today.getHours() + 4);
It will not cause an error if you try to add 4 to 23 (see the documentation):
If a parameter you specify is outside of the expected range, setHours() attempts to update the date information in the Date object accordingly
It is probably better to make the addHours method immutable by returning a copy of the Date object rather than mutating its parameter.
Date.prototype.addHours= function(h){
var copiedDate = new Date(this.getTime());
copiedDate.setHours(copiedDate.getHours()+h);
return copiedDate;
}
This way you can chain a bunch of method calls without worrying about state.
The version suggested by kennebec will fail when changing to or from DST, since it is the hour number that is set.
this.setUTCHours(this.getUTCHours()+h);
will add h hours to this independent of time system peculiarities.
Jason Harwig's method works as well.
Get a date exactly two hours from now, in one line.
You need to pass milliseconds to new Date.
let expiryDate = new Date(new Date().setHours(new Date().getHours() + 2));
or
let expiryDate2 = new Date(Date.now() + 2 * (60 * 60 * 1000) );
let nowDate = new Date();
let expiryDate = new Date(new Date().setHours(new Date().getHours() + 2));
let expiryDate2 = new Date(Date.now() + 2 * (60 * 60 * 1000) );
console.log('now', nowDate);
console.log('expiry', expiryDate);
console.log('expiry 2', expiryDate2);
You can use the Moment.js library.
var moment = require('moment');
foo = new moment(something).add(10, 'm').toDate();
I also think the original object should not be modified. So to save future manpower here's a combined solution based on Jason Harwig's and Tahir Hasan answers:
Date.prototype.addHours= function(h){
var copiedDate = new Date();
copiedDate.setTime(this.getTime() + (h*60*60*1000));
return copiedDate;
}
If you would like to do it in a more functional way (immutability) I would return a new date object instead of modifying the existing and I wouldn't alter the prototype but create a standalone function. Here is the example:
//JS
function addHoursToDate(date, hours) {
return new Date(new Date(date).setHours(date.getHours() + hours));
}
//TS
function addHoursToDate(date: Date, hours: number): Date {
return new Date(new Date(date).setHours(date.getHours() + hours));
}
let myDate = new Date();
console.log(myDate)
console.log(addHoursToDate(myDate,2))
There is an add in the Datejs library.
And here are the JavaScript date methods. kennebec wisely mentioned getHours() and setHours();
Check if it’s not already defined. Otherwise, define it in the Date prototype:
if (!Date.prototype.addHours) {
Date.prototype.addHours = function(h) {
this.setHours(this.getHours() + h);
return this;
};
}
This is an easy way to get an incremented or decremented data value.
const date = new Date()
const inc = 1000 * 60 * 60 // an hour
const dec = (1000 * 60 * 60) * -1 // an hour
const _date = new Date(date)
return new Date(_date.getTime() + inc)
return new Date(_date.getTime() + dec)
Another way to handle this is to convert the date to unixtime (epoch), then add the equivalent in (milli)seconds, then convert it back. This way you can handle day and month transitions, like adding 4 hours to 21, which should result in the next day, 01:00.
SPRBRN is correct. In order to account for the beginning/end of the month and year, you need to convert to Epoch and back.
Here's how you do that:
var milliseconds = 0; //amount of time from current date/time
var sec = 0; //(+): future
var min = 0; //(-): past
var hours = 2;
var days = 0;
var startDate = new Date(); //start date in local time (we'll use current time as an example)
var time = startDate.getTime(); //convert to milliseconds since epoch
//add time difference
var newTime = time + milliseconds + (1000*sec) + (1000*60*min) + (1000*60*60*hrs) + (1000*60*60*24*days);
var newDate = new Date(newTime); //convert back to date; in this example: 2 hours from right now
Or do it in one line (where variable names are the same as above:
var newDate =
new Date(startDate.getTime() + millisecond +
1000 * (sec + 60 * (min + 60 * (hours + 24 * days))));
For a simple add/subtract hour/minute function in JavaScript, try this:
function getTime (addHour, addMin){
addHour = (addHour ? addHour : 0);
addMin = (addMin ? addMin : 0);
var time = new Date(new Date().getTime());
var AM = true;
var ndble = 0;
var hours, newHour, overHour, newMin, overMin;
// Change form 24 to 12 hour clock
if(time.getHours() >= 13){
hours = time.getHours() - 12;
AM = (hours>=12 ? true : false);
}else{
hours = time.getHours();
AM = (hours>=12 ? false : true);
}
// Get the current minutes
var minutes = time.getMinutes();
// Set minute
if((minutes + addMin) >= 60 || (minutes + addMin) < 0){
overMin = (minutes + addMin) % 60;
overHour = Math.floor((minutes + addMin - Math.abs(overMin))/60);
if(overMin < 0){
overMin = overMin + 60;
overHour = overHour-Math.floor(overMin/60);
}
newMin = String((overMin<10 ? '0' : '') + overMin);
addHour = addHour + overHour;
}else{
newMin = minutes + addMin;
newMin = String((newMin<10 ? '0' : '') + newMin);
}
// Set hour
if((hours + addHour >= 13) || (hours + addHour <= 0)){
overHour = (hours + addHour) % 12;
ndble = Math.floor(Math.abs((hours + addHour)/12));
if(overHour <= 0){
newHour = overHour + 12;
if(overHour == 0){
ndble++;
}
}else{
if(overHour == 0){
newHour = 12;
ndble++;
}else{
ndble++;
newHour = overHour;
}
}
newHour = (newHour<10 ? '0' : '') + String(newHour);
AM = ((ndble + 1) % 2 === 0) ? AM : !AM;
}else{
AM = (hours + addHour == 12 ? !AM : AM);
newHour = String((Number(hours) + addHour < 10 ? '0': '') + (hours + addHour));
}
var am = (AM) ? 'AM' : 'PM';
return new Array(newHour, newMin, am);
};
This can be used without parameters to get the current time:
getTime();
Or with parameters to get the time with the added minutes/hours:
getTime(1, 30); // Adds 1.5 hours to current time
getTime(2); // Adds 2 hours to current time
getTime(0, 120); // Same as above
Even negative time works:
getTime(-1, -30); // Subtracts 1.5 hours from current time
This function returns an array of:
array([Hour], [Minute], [Meridian])
If you need it as a string, for example:
var defaultTime: new Date().getHours() + 1 + ":" + new Date().getMinutes();
I think this should do the trick
var nextHour = Date.now() + 1000 * 60 * 60;
console.log(nextHour)
You can even format the date in desired format using the moment function after adding 2 hours.
var time = moment(new Date(new Date().setHours(new Date().getHours() + 2))).format("YYYY-MM-DD");
console.log(time);
A little messy, but it works!
Given a date format like this: 2019-04-03T15:58
//Get the start date.
var start = $("#start_date").val();
//Split the date and time.
var startarray = start.split("T");
var date = startarray[0];
var time = startarray[1];
//Split the hours and minutes.
var timearray = time.split(":");
var hour = timearray[0];
var minute = timearray[1];
//Add an hour to the hour.
hour++;
//$("#end_date").val = start;
$("#end_date").val(""+date+"T"+hour+":"+minute+"");
Your output would be: 2019-04-03T16:58
The easiest way to do it is:
var d = new Date();
d = new Date(d.setHours(d.getHours() + 2));
It will add 2 hours to the current time.
The value of d = Sat Jan 30 2021 23:41:43 GMT+0500 (Pakistan Standard Time).
The value of d after adding 2 hours = Sun Jan 31 2021 01:41:43 GMT+0500 (Pakistan Standard Time).

How to convert datetime to UTC+1 in JavaScript

We have created a function in node-red, where we cleaning a datetime received from the metadata of a sensor. Unfortunately, the timezone fetched is one hour behind, and therefore a "wrong datetime" is sent. We need to convert this datetime to UTC+1 ('Europe/Berlin'). The function is in JavaScript, and in my knowledge we can't use third party libraries like moment etc.
Hopefully, someone here can help us. Thanks in advance!
This is what we have done so far:
var time = msg.metadata.time;
var datetime = new Date().toLocaleString();
var timedate = new Date(time);
var y = timedate.getFullYear().toString();
var m = (timedate.getMonth() + 1).toString();
var d = timedate.getDate().toString();
(d.length == 1) && (d = '0' + d);
(m.length == 1) && (m = '0' + m);
timedate.setHours(timedate.getHours() + 1)
var h = timedate.getHours().toString();
var min = timedate.getMinutes().toString();
var s = timedate.getSeconds().toString();
(h.length == 1) && (h = '0' + h);
(min.length == 1) && (min = '0' + min);
(s.length == 1) && (s = '0' + s);
var date = y+'-'+m+'-'+d
var time = h + ":" + min + ":" + s;
var timeDate = date+' '+time;
I would consider using Date.toLocaleString() for date/time conversion.
Now Moment.js will be better if you can use it, but you can convert times like below.
Remember you must consider DST changes and these are hard to account for using your own code (the exact dates of DST switchover change from year to year).
For example, Berlin uses CET (UTC+1) from late October to late March and CEST (UTC+2) from late March to late October.
Why am I using a locale of "sv", this is because it will essentially give us an ISO 8601 timestamp. Of course for converting to text you can use any locale.
I've added a getUTCOffsetMinutes function that will return the UTC offset in minutes for a given UTC time and timezone.
A list of IANA timezones is here: timezone list
const time = 1559347200000; // 2019-06-01T00:00:00Z
console.log("UTC time 1:", new Date(time).toISOString());
console.log("Berlin time 1 (ISO):", new Date(time).toLocaleString("sv", { timeZone: "Europe/Berlin"}));
console.log("Berlin time 1 (de):", new Date(time).toLocaleString("de", { timeZone: "Europe/Berlin"}));
const time2 = 1575158400000; // 2019-12-01T00:00:00Z
console.log("UTC time 2:", new Date(time2).toISOString());
console.log("Berlin time 2 (ISO):", new Date(time2).toLocaleString("sv", { timeZone: "Europe/Berlin"}));
console.log("Berlin time 2 (de):", new Date(time2).toLocaleString("de", { timeZone: "Europe/Berlin"}));
// You can also get the UTC offset using a simple enough function:
// Again, this will take into account DST
function getUTCOffsetMinutes(unixDate, tz) {
const localTimeISO = new Date(unixDate).toLocaleString("sv", {timeZone: tz}).replace(" ", "T") + "Z";
return (new Date(localTimeISO).getTime() - unixDate) / 60000; // Milliseconds to minutes.
}
console.log("UTC offset minutes (June/Berlin):", getUTCOffsetMinutes(time, "Europe/Berlin"));
console.log("UTC offset minutes (June/LA):", getUTCOffsetMinutes(time, "America/Los_Angeles"));
console.log("UTC offset minutes (June/Sydney):",getUTCOffsetMinutes(time, "Australia/Sydney"));
console.log("UTC offset minutes (December/Berlin):", getUTCOffsetMinutes(time2, "Europe/Berlin"));
console.log("UTC offset minutes (December/LA):", getUTCOffsetMinutes(time2, "America/Los_Angeles"));
console.log("UTC offset minutes (December/Sydney):", getUTCOffsetMinutes(time2, "Australia/Sydney"));
I use this function I made, i think it may help you:
function formatDateToOffset(date, timeOffset){
var dateInfo, timeInfo;
// change date's hours based on offset
date.setHours(date.getHours() + (timeOffset || 0))
// place it the way you want to format
dateInfo = [date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()]
timeInfo = [date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()];
// return the string formatted date
return dateInfo.join("-") + " " + timeInfo.join(":");
}
console.log(formatDateToOffset(new Date(), 1))

extract total minutes between two times using jquery

I have two times which are in 12 hours format. Example 10:00 am and 3:30 pm. I want to show 330 minutes between them. I have tried many ways but couldn't get accurate result.
my script:
time1= 'yy/mm/dd 10:00 am';
time2='yy/mm/dd 3:30 pm';
from1 = new Date(time1);
to1 = new Date(time2);
console.log(from1-to1);
I don't usually like writing code for people, but I'm feeling nice today.
function parse12hToMin(timeStr){ //returns the minutes as an offset from 12:00 AM
let match12h = new RegExp(
"^" + // start of string
"(1[0-2]|[1-9])" + // hour
":" + // separator
"([0-5][0-9])" + // minutes
" " + // separator
"(am|pm)" // AM or PM
, 'i'); // case insensitive
let matched = timeStr.match(match12h);
let min = parseInt(matched[1]) * 60 // hours
+ parseInt(matched[2]) // minutes
+ (matched[3].toLowerCase() === "pm" ? 720 : 0); // 720 min PM offset
return min;
}
function minutesDiff12h(start, end){
return parse12hToMin(end) - parse12hToMin(start);
}
console.assert(minutesDiff12h("10:00 am","3:30 pm") === 330);
Please always try to list what you tried, and show us the code snippets that aren't working.
I would isolate the hours part of your time and use 24hr time to make things easier.
var start_time ="1000";
var end_time ="1530";
var start_hour = start_time.slice(0, -2);
var start_minutes = start_time.slice(-2);
var end_hour = end_time.slice(0, -2);
var end_minutes = end_time.slice(-2);
var startDate = new Date(0,0,0, start_hour, start_minutes);
var endDate = new Date(0,0,0, end_hour, end_minutes);
var millis = endDate - startDate;
var minutes = millis/1000/60;
console.log(minutes);

How to add minutes and hours to a time string using jquery

I want to add 30 minutes and then one hour to my variable which i already have my own date
var initialDate = '10:00';
So
if (some condition){
// i add 30 minutes ->10:30
}elseif(another condition){
// i add 1hour ->11:00
}
I tried this but doesn't work
var initialDate = '10:00';
var theAdd = new Date(initialDate);
var finalDate = theAdd.setMinutes(theAdd.getMinutes() + 30);
If I understand you correctly, the following will help you.
You need to add momentjs dependency via script tag and you can Parse, validate, manipulate, and display dates in JavaScript.
You can find more documentation regarding this in momentjs website
console.log(moment.utc('10:00','hh:mm').add(1,'hour').format('hh:mm'));
console.log(moment.utc('10:00','hh:mm').add(30,'minutes').format('hh:mm'));
<script src="https://momentjs.com/downloads/moment-with-locales.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var theAdd = new Date();
// Set Hours, minutes, secons and miliseconds
theAdd.setHours(10, 00, 00, 000);
if (some condition) {
// add 30 minutes --> 10:30
theAdd.setMinutes(theAdd.getMinutes() + 30);
}
elseif (some condition) {
// add 1 hour --> 11:00
theAdd.setHours(theAdd.getHours() + 1);
}
Then you print the var theAdd to obtain the date and time.
To obtain just the time:
theAdd.getHours() + ":" + theAdd.getMinutes();
This should do the job. Dates need a year and month in their constructor, and you have to specify larger units of time if you specify and smaller ones, so it needs a day as well. Also, you have to pass in the hours and minutes separately. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date.
var initialDate = '10:00';
var theAdd = new Date(1900,0,1,initialDate.split(":")[0],initialDate.split(":")[1]);
if(30 min condition){
theAdd.setMinutes(theAdd.getMinutes() + 30);
} else if (1 hour condition){
theAdd.setHours(theAdd.getHours() + 1);
}
console.log(theAdd.getHours()+":"+theAdd.getMinutes());
Here is a javascript function that will add minutes to hh:mm time string.
function addMinutes(timeString, addMinutes) {
if (!timeString.match(/^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/))
return null;
var timeSplit = timeString.split(':');
var hours = parseInt(timeSplit[0]);
var minutes = parseInt(timeSplit[1]) + parseInt(addMinutes);
hours += Math.floor(minutes / 60);
while (hours >= 24) {
hours -= 24;
}
minutes = minutes % 60;
return ('0' + hours).slice(-2) + ':' + ('0' +minutes).slice(-2);
}

Jquery time difference in hours from two fields

I have two fields in my form where users select an input time (start_time, end_time) I would like to, on the change of these fields, recalcuate the value for another field.
What I would like to do is get the amount of hours between 2 times. So for instance if I have a start_time of 5:30 and an end time of 7:50, I would like to put the result 2:33 into another field.
My inputted form times are in the format HH:MM:SS
So far I have tried...
$('#start_time,#end_time').on('change',function()
{
var start_time = $('#start_time').val();
var end_time = $('#end_time').val();
var diff = new Date(end_time) - new Date( start_time);
$('#setup_hours').val(diff);
try
var diff = ( new Date("1970-1-1 " + end_time) - new Date("1970-1-1 " + start_time) ) / 1000 / 60 / 60;
have a fiddle
It depends on what format you want your output in. When doing math with Date objects, it converts them into milliseconds since Epoch time (January 1, 1970, 00:00:00 UTC). By subtracting the two (and taking absolute value if you don't know which is greater) you get the raw number of milliseconds between the two.
From there, you can convert it into whatever format you want. To get the number of seconds, just divide that number by 1000. To get hours, minutes, and seconds:
var diff = Math.abs(new Date(end_time) - new Date(start_time));
var seconds = Math.floor(diff/1000); //ignore any left over units smaller than a second
var minutes = Math.floor(seconds/60);
seconds = seconds % 60;
var hours = Math.floor(minutes/60);
minutes = minutes % 60;
alert("Diff = " + hours + ":" + minutes + ":" + seconds);
You could of course make this smarter with some conditionals, but this is just to show you that using math you can format it in whatever form you want. Just keep in mind that a Date object always has a date, not just a time, so you can store this in a Date object but if it is greater than 24 hours you will end up with information not really representing a "distance" between the two.
var start = '5:30';
var end = '7:50';
s = start.split(':');
e = end.split(':');
min = e[1]-s[1];
hour_carry = 0;
if(min < 0){
min += 60;
hour_carry += 1;
}
hour = e[0]-s[0]-hour_carry;
min = ((min/60)*100).toString()
diff = hour + ":" + min.substring(0,2);
alert(diff);
try this :
var diff = new Date("Aug 08 2012 9:30") - new Date("Aug 08 2012 5:30");
diff_time = diff/(60*60*1000);

Categories