jQuery How to parse start and end time hour by hour - javascript

I have issues, i working with time mode, and now i have two values is:
var startTime = "05:45:00 22/05/19"
var endTime = "14:45:00 22/05/19"
So problem is, i need to parse this date by hours.
Result must be:
05:45 - 06:00
06:00 - 07:00
07:00 - 08:00
08:00 - 09:00
09:00 - 10:00
10:00 - 11:00
11:00 - 12:00
12:00 - 13:00
13:00 - 14:00
14:00 - 14:45
As u can see i need not standart parsing hours.
So i try to use this method:
function addMinutes(time, minutes) {
var date = new Date(new Date('01/01/2015 ' + time).getTime() + minutes * 60000);
var tempTime = ((date.getHours().toString().length == 1) ? '0' + date.getHours() : date.getHours()) + ':' +
((date.getMinutes().toString().length == 1) ? '0' + date.getMinutes() : date.getMinutes()) + ':' +
((date.getSeconds().toString().length == 1) ? '0' + date.getSeconds() : date.getSeconds());
return tempTime;
}
var starttime = "05:45:00";
var interval = "60";
var endtime = "14:45:00";
var timeslots = [starttime];
while (starttime != endtime) {
starttime = addMinutes(starttime, interval);
timeslots.push(starttime);
}
console.log(timeslots);
OUTPUT:
0: "05:45:00"
1: "06:45:00"
2: "07:45:00"
3: "08:45:00"
4: "09:45:00"
5: "10:45:00"
6: "11:45:00"
7: "12:45:00"
8: "13:45:00"
9: "14:45:00"
But for me it's not good, plus if end date is for next date it's not calculate

Here is a solution :
loop from start hour to end hour and check if we are on the first hour or end hour to do some specific code otherwise render startHour - startHour +1
var startTime = "15:00"
var endTime = "00:15"
var timeslots = [];
var startOffset = parseInt(startTime.substring(0,2));
var endOffset = parseInt(endTime.substring(0,2));
if(endOffset < startOffset){
endOffset+= 24;
}
for(var i = startOffset;i<=endOffset;i++){
var begin,end;
var currentOffset = i < 24 ? i : i - 24;
if(i==startOffset){
begin = startTime;
}else{
begin = currentOffset < 10 ? "0" + currentOffset +":00" : currentOffset +":00" ;
}
if(i==endOffset){
end = endTime;
}else{
end = currentOffset < 9 ? "0" + (currentOffset+1) +":00" :(currentOffset+1) +":00";
}
timeslots.push(begin + " : " + end);
}
console.log(timeslots);

I did it like this. It still requires additional parsing, if you want to remove seconds.
function timestringToDate(time) {
var temptime = new Date();
var splittedtime = time.split(':');
temptime.setHours(splittedtime[0], splittedtime[1], 0);
return temptime;
}
var starttime = "05:45:00";
var endtime = "14:45:00";
var starttimeobj = timestringToDate(starttime);
var endtimeobj = timestringToDate(endtime);
var slotarray = [];
var slotstart, slotend;
for(var t = starttimeobj; t.getHours() < endtimeobj.getHours(); ) {
slotstart = t.toLocaleTimeString('en-US', { hour12: false });
t.setHours(t.getHours()+1);
if(t.getMinutes !== 0)
t.setMinutes(0);
slotend = t.toLocaleTimeString('en-US', { hour12: false });
slotarray.push(slotstart + ' - ' + slotend);
}
slotarray.push(slotend + ' - ' + endtimeobj.toLocaleTimeString('en-US', { hour12: false })); /* I add last hour */
console.log(slotarray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related

Getting issue while calculating the time difference using JavaScript

I am facing some issue while calculating the time difference between two dates using the JavaScript. I am providing my code below.
Here I have cutoff time and dep_time value. I have to calculate today's date with dep_date and if today's date and time is before the cutoff time then it will return true otherwise false. In my case its working fine in Chrome but for same function it's not working in Firefox. I need it to work for all browsers.
function checkform() {
var dep_date = $("#dep_date1").val(); //07/27/2019
var cut_offtime = $("#cutoff_time").val(); //1
var dep_time = $("#dep_time").val(); //6:00pm
var dep_time1 = dep_time.replace(/[ap]/, " $&");
var todayDate = new Date();
var todayMonth = todayDate.getMonth() + 1;
var todayDay = todayDate.getDate();
var todayYear = todayDate.getFullYear();
if (todayDay < 10) {
todayDay = "0" + todayDay;
}
if (todayMonth < 10) {
todayMonth = "0" + todayMonth;
}
//console.log('both dates',todayMonth,todayDay,todayYear);
var todayDateText = todayMonth + "-" + todayDay + "-" + todayYear;
var inputToDate = Date.parse(dep_date.replace(/\//g, " "));
var todayToDate = Date.parse(todayDateText.replace(/-/g, " "));
console.log("both dates", dep_date, todayDateText);
if (inputToDate >= todayToDate) {
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? "pm" : "am";
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? "0" + minutes : minutes;
var strTime = hours + ":" + minutes + " " + ampm;
var timeStart = new Date(todayDateText + " " + strTime);
var timeEnd = new Date(dep_date + " " + dep_time1);
var diff = (timeEnd - timeStart) / 60000; //dividing by seconds and milliseconds
var minutes = diff % 60;
var hours = (diff - minutes) / 60;
console.log("hr", hours);
if (parseInt(hours) > parseInt(cut_offtime)) {
return true;
} else {
alert("You should book this trip before " + cut_offtime + " hr");
return false;
}
} else {
alert("You should book this trip before " + cut_offtime + " hr");
return false;
}
}
Part of your issue is here:
var todayDateText = todayMonth + "-" + todayDay + "-" + todayYear;
var inputToDate = Date.parse(dep_date.replace(/\//g, " "));
The first line generates a string like "07-17-2019". The next changes it to "07 17 2019" and gives it to the built–in parser. That string is not a format supported by ECMA-262 so parsing is implementation dependent.
Chrome and Firefox return a date for 17 July 2019, Safari returns an invalid date.
It doesn't make sense to parse a string to get the values, then generate another string to be parsed by the built–in parser. Just give the first set of values directly to the Date constructor:
var inputToDate = new Date(todayYear, todayMonth - 1, todayDay);
which will work in every browser that ever supported ECMAScript.
Similarly:
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? "pm" : "am";
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? "0" + minutes : minutes;
var strTime = hours + ":" + minutes + " " + ampm;
var timeStart = new Date(todayDateText + " " + strTime);
appears to be a lengthy and brittle way to copy a date and set the seconds and milliseconds to zero. The following does exactly that in somewhat less code:
var date = new Date();
var timeStart = new Date(date);
timeStart.setMinutes(0,0);
use
var timeStart = new Date(todayDateText + " " + strTime)
Applying these changes to your code gives something like:
function parseMDY(s) {
var b = s.split(/\D/);
return new Date(b[2], b[0]-1, b[1]);
}
function formatDate(d) {
return d.toLocaleString(undefined, {
day: 'numeric',
month: 'short',
year: 'numeric'
});
}
// Call function with values
function checkform(dep_date, cut_offtime, dep_time) {
// Helper
function z(n) {
return (n<10?'0':'') + n;
}
// Convert dep_date to Date
var depD = parseMDY(dep_date);
// Get the departure time parts
var dtBits = dep_time.toLowerCase().match(/\d+|[a-z]+/gi);
var depHr = +dtBits[0] + (dtBits[2] == 'pm'? 12 : 0);
var depMin = +dtBits[1];
// Set the cutoff date and time
var cutD = new Date(depD);
cutD.setHours(depHr, depMin, 0, 0);
// Get current date and time
var now = new Date();
// Create cutoff string
var cutHr = cutD.getHours();
var cutAP = cutHr > 11? 'pm' : 'am';
cutHr = z(cutHr % 12 || 12);
cutMin = z(cutD.getMinutes());
var cutStr = cutHr + ':' + cutMin + ' ' + cutAP;
var cutDStr = formatDate(cutD);
// If before cutoff, OK
if (now < cutD) {
alert('Book before ' + cutStr + ' on ' + cutDStr);
return true;
// If after cutoff, not OK
} else {
alert('You should have booked before ' + cutStr + ' on ' + cutDStr);
return false;
}
}
// Samples
checkform('07/27/2019','1','6:00pm');
checkform('07/17/2019','1','11:00pm');
checkform('07/07/2019','1','6:00pm');
That refactors your code somewhat, but hopefully shows how to improve it and fix the parsing errors.

Could not calculate the time difference using JavaScript

I need to calculate time difference in hrs in between current date time and user input date time using JavaScript. Here is my code:
var user_date = '31-03-2019';
var dep_time='12:30PM';
var datePieces = user_date.split("-");
var mydate=[datePieces[1] , datePieces[0] , datePieces[2]].join("-");
var todayDate = new Date();
var todayMonth = todayDate.getMonth() + 1;
var todayDay = todayDate.getDate();
var todayYear = todayDate.getFullYear();
if (todayDay < 10) {
todayDay = '0' + todayDay;
}
if (todayMonth < 10) {
todayMonth = '0' + todayMonth;
}
var todayDateText = todayMonth + "-" + todayDay + "-" + todayYear;
var inputToDate = Date.parse(mydate);
var todayToDate = Date.parse(todayDateText);
//console.log(inputToDate, todayToDate);
//console.log(user_date, todayDateText);
if (inputToDate > todayToDate) {
var date=new Date;
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
var timeStart = new Date(todayToDate + strTime);
var timeEnd = new Date(mydate + dep_time);
console.log(timeStart);
console.log(timeEnd);
var diff = (timeEnd - timeStart) / 60000; //dividing by seconds and milliseconds
var minutes = diff % 60;
var hours = (diff - minutes) / 60;
alert(hours);
} else {
}
Here I getting the output NAN . I have both user input and current date time and I need the time difference in HRS.
1) The Date.parse method turns a date into milliseconds since January 1st, 1970. See https://www.w3schools.com/Jsref/jsref_parse.asp, therefore turning your user input date into milliseconds since January 1st, 1970.
2) In Javascript, the getTime() method on the new Date() object gets the number of milliseconds that have passed since January 1, 1970 until the current time.
3) Therefore, finding the difference of these milliseconds gives you the difference in milliseconds.
4) Since 1 hour = 3600000 ms, to find the difference in hours, divide your answer by 3600000, and get the difference in hours.
You also seem to forget to include the dep_time in parsing your date.
And the solution is below:
<script>
"use strict";
var user_date = '31-03-2019 12:30 PM';
var datePieces = user_date.split("-");
var mydate=[datePieces[1] , datePieces[0] , datePieces[2]].join("-");
var todayDate = new Date();
var todayToDate = todayDate.getTime();
// In JavaScript, getTime() gets the number of milliseconds that have passed since January 1, 1970.
var inputToDate = Date.parse(mydate);
if (inputToDate > todayToDate) {
var diff = (inputToDate - todayToDate) / 3600000; //Since 1 h = 3600000 ms
alert(diff);
} else {
var diff = (todayToDate - inputToDate) / 3600000; //Since 1 h = 3600000 ms
alert(diff);
}
</script>

output correct format 24 hour after calculation

I'm currently using this function to calculate 2 fields and the results are good but sometimes missing a zero. sample
10:20 + 10:30 current output 0.10
10:20 + 10:30 I want the output to be 00.10
$(function () {
function calculate() {
time1 = $("#start").val().split(':'),
time2 = $("#end").val().split(':');
hours1 = parseInt(time1[0], 10),
hours2 = parseInt(time2[0], 10),
mins1 = parseInt(time1[1], 10),
mins2 = parseInt(time2[1], 10);
hours = hours2 - hours1,
mins = 0;
if(hours < 0) hours = 24 + hours;
if(mins2 >= mins1) {
mins = mins2 - mins1;
} else {
mins = (mins2 + 60) - mins1;
}
// the result
$("#hours").val(hours + ':' + mins);
}
});
also when there is an invalid character I keep getting a nan message is possible to change this to 00 instead?
Instead of dealing with the strings and each value independently, you can use the javascript Date object to calculate the difference...
function calculate() {
// Get time values and convert them to javascript Date objects.
var time1 = new Date('01/01/2017 ' + $('#start').val());
var time2 = new Date('01/01/2017 ' + $('#end').val());
// Get the time difference in minutes. If is negative, add 24 hours.
var hourDiff = (time2 - time1) / 60000;
hourDiff = (hourDiff < 0) ? hourDiff+1440 : hourDiff;
// Calculate hours and minutes.
var hours = Math.floor(hourDiff/60);
var minutes = Math.floor(hourDiff%60);
// Set the result adding '0' to the left if needed
$("#hours").val((hours<10 ? '0'+hours : hours) + ':' + (minutes<10 ? '0'+minutes : minutes));
}
Or even better, you can make the function independent of the DOM elements, so you can reuse it...
function calculate(startTime,endTime) {
// Get time values and convert them to javascript Date objects.
var time1 = new Date('01/01/2017 ' + startTime);
var time2 = new Date('01/01/2017 ' + endTime);
// Get the time difference in minutes. If is negative, add 24 hours.
var hourDiff = (time2 - time1) / 60000;
hourDiff = (hourDiff < 0) ? hourDiff+1440 : hourDiff;
// Calculate hours and minutes.
var hours = Math.floor(hourDiff/60);
var minutes = Math.floor(hourDiff%60);
// Return the response, adding '0' to the left of each field if needed.
return (hours<10 ? '0'+hours : hours) + ':' + (minutes<10 ? '0'+minutes : minutes);
}
// Now you can use the function.
$("#hours").val(calculate($('#start').val(),$('#end').val()));
Add a function
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
and call this function before displaying result
I propose you that :
$(".calculator").on("change",function(){
var isNegative = false;
var hours = "00:00";
var inputStart = $("#start").val();
var inputEnd = $("#end").val();
if(inputStart!="" && inputEnd != ""){
// calculate only if the 2 fields have inputs
// convert to seconds (more convenient)
var seconds1 = stringToSeconds(inputStart);
var seconds2 = stringToSeconds(inputEnd);
var secondsDiff = seconds2 - seconds1;
var milliDiffs = secondsDiff * 1000;
if(milliDiffs < 0){
milliDiffs = milliDiffs *-1;
isNegative = true;
}
// Convert the difference to date
var diff = new Date(milliDiffs);
// convert the date to string
hours = diff.toUTCString();
// extract the time information in the string 00:00:00
var regex = new RegExp(/[0-9]{2}:[0-9]{2}:[0-9]{2}/);
var arr = hours.match(regex);
hours = arr[0];
// Take only hours and minutes and leave the seconds
arr = hours.split(":");
hours=arr[0]+":"+arr[1];
// put minus in front if negative
if(isNegative){
hours = "-"+hours;
}
// Show the result
$("#hours").val(hours);
// Put back the inputs times in case there were somehow wrong
// (it's the same process)
var date1 = new Date(seconds1*1000);
var str1 = date1.toUTCString();
arr = str1.match(regex);
hours = arr[0];
arr = hours.split(":");
hours=arr[0]+":"+arr[1];
$("#start").val(hours);
// idem for time 2
var date2 = new Date(seconds2*1000);
var str2 = date2.toUTCString();
arr = str2.match(regex);
hours = arr[0];
arr = hours.split(":");
hours=arr[0]+":"+arr[1];
$("#end").val(hours);
}
});
function timeElementToString(timeElement){
var output = timeElement.toString();
if(timeElement < 10 && timeElement >=0)
output = "0"+output;
else if(timeElement < 0 && timeElement >=-10)
output = "-0"+Math.abs(output);
return output;
}
function stringToSeconds(input){
var hours = 0;
var arr=input.split(":");
if(arr.length==2){
hours=parseInt(arr[0]);
minutes=parseInt(arr[1]);
if(isNaN(hours)){
hours = 0;
}
if(isNaN(minutes)){
minutes = 0;
}
}
return hours*3600+60*minutes;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="start">Start</label><input type="text" id="start" class="calculator"></input><br />
<label for="end">End</label><input type="text" id="end" class="calculator"></input><br />
<label for="hours">Hours</label><input type="text" id="hours" readonly="readonly"></input>
</form>

check time in between Time Slot

Check the Selected time should is exist in between the time slot.
var selectedTime = 01:30 AM
var startTime = 12:00 AM
var endTime = 01:00 PM
/* need logic below in below code without date in Date Object*/
var startTime = Date.parse('01/01/2001 '+startTime);
var endTime = Date.parse('01/01/2001 '+endTime);
if(selectedTime <= startTime && selectedTime >= endTime)
{
alert("Time in beween interval");
}else{
alert("Time is not with in the time Slot");
}
Using this : Convert HH:MM:SS string to seconds only in javascript
I have created this : https://jsfiddle.net/ceyh4ens/
Only works with 24 hour clocks for the time being, but some simple logic will get around this. The main parts are :
var selectedTimeSeconds = selectedTime.substring(0,5) + ':00'; //splits the string into hours minutes and seconds
If you want to work with 12 hour clocks, you could do more parsing here.
And now your if statements should work :)
var selectedTime = '11:30 PM'
var startTime = '12:00 AM'
var endTime = '13:00 AM'
var selectedTimeSeconds = selectedTime.substring(0,5) + ':00';
var startTimeSeconds = startTime.substring(0,5) + ':00';
var endTimeSeconds = endTime.substring(0,5) + ':00';
var selectedTimeSecondsParsed = hmsToSecondsOnly(selectedTimeSeconds) //pass to convert to seconds function
var startTimeSecondsParsed = hmsToSecondsOnly(startTimeSeconds)
var endTimeSecondssParsed = hmsToSecondsOnly(endTimeSeconds)
console.log(selectedTimeSecondsParsed)
console.log(startTimeSecondsParsed)
console.log(endTimeSecondssParsed)
/* need logic to convert time to Date Format */
if (selectedTimeSecondsParsed >= startTimeSecondsParsed && selectedTimeSecondsParsed <= endTimeSecondssParsed) { //if its between
alert("Time in beween interval");
} else {
alert("Time is not with in the time Slot");
}
function hmsToSecondsOnly(str) {
var p = str.split(':'),
s = 0,
m = 1;
while (p.length > 0) {
s += m * parseInt(p.pop(), 10);
m *= 60;
}
return s;
}
EDIT
To work with 24 hours you need to check whether its AM or PM. If it's PM, add 12 hours, if it's AM do nothing. Here's the function that does that check :
function changeTime(time) {
var thisTime;
var thisHour = +time.substring(0, 2);
if (time.substring(6, 8) == 'PM') {
//add 12 hours to make it 24 hour clock
thisHour += 12;
}
return thisHour + time.substring(2, 5);//concatenate with the rest
}
Then just pass your string like so :
var selectedTimeSeconds = changeTime(selectedTime);
Working updated fiddle : https://jsfiddle.net/jszuLo9o/

Converting 24 hour time to 12 hour time w/ AM & PM using Javascript

What is the best way to convert the following JSON returned value from a 24-hour format to 12-hour format w/ AM & PM? The date should stay the same - the time is the only thing that needs formatting.
February 04, 2011 19:00:00
P.S. Using jQuery if that makes it any easier! Would also prefer a simple function/code and not use Date.js.
This is how you can change hours without if statement:
hours = ((hours + 11) % 12 + 1);
UPDATE 2: without seconds option
UPDATE: AM after noon corrected, tested: http://jsfiddle.net/aorcsik/xbtjE/
I created this function to do this:
function formatDate(date) {
var d = new Date(date);
var hh = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var dd = "AM";
var h = hh;
if (h >= 12) {
h = hh - 12;
dd = "PM";
}
if (h == 0) {
h = 12;
}
m = m < 10 ? "0" + m : m;
s = s < 10 ? "0" + s : s;
/* if you want 2 digit hours:
h = h<10?"0"+h:h; */
var pattern = new RegExp("0?" + hh + ":" + m + ":" + s);
var replacement = h + ":" + m;
/* if you want to add seconds
replacement += ":"+s; */
replacement += " " + dd;
return date.replace(pattern, replacement);
}
alert(formatDate("February 04, 2011 12:00:00"));
//it is pm if hours from 12 onwards
suffix = (hours >= 12)? 'pm' : 'am';
//only -12 from hours if it is greater than 12 (if not back at mid night)
hours = (hours > 12)? hours -12 : hours;
//if 00 then it is 12 am
hours = (hours == '00')? 12 : hours;
For anyone reading who wants ONLY the time in the output, you can pass options to JavaScript's Date::toLocaleString() method. Example:
var date = new Date("February 04, 2011 19:00:00");
var options = {
hour: 'numeric',
minute: 'numeric',
hour12: true
};
var timeString = date.toLocaleString('en-US', options);
console.log(timeString);
timeString will be set to:
8:00 AM
Add "second: 'numeric'" to your options if you want seconds too. For all option see this.
Here's a reasonably terse way to do it using a Prototype:
Date.prototype.getFormattedTime = function () {
var hours = this.getHours() == 0 ? "12" : this.getHours() > 12 ? this.getHours() - 12 : this.getHours();
var minutes = (this.getMinutes() < 10 ? "0" : "") + this.getMinutes();
var ampm = this.getHours() < 12 ? "AM" : "PM";
var formattedTime = hours + ":" + minutes + " " + ampm;
return formattedTime;
}
Then all you have to do is convert your string value to a date and use the new method:
var stringValue = "February 04, 2011 19:00:00;
var dateValue = new Date(stringValue);
var formattedTime = dateValue.getFormattedTime();
Or in a single line:
var formattedTime = new Date("February 04, 2011 19:00:00").getFormattedTime();
Keep it simple and clean
var d = new Date();
var n = d.toLocaleString();
https://jsfiddle.net/rinu6200/3dkdxaad/#base
function pad(num) {return ("0" + num).slice(-2);}
function time1() {
var today = new Date(),
h = today.getHours(),
m = today.getMinutes(),
s = today.getSeconds();
h = h % 12;
h = h ? h : 12; // the hour '0' should be '12'
clk.innerHTML = h + ':' +
pad(m) + ':' +
pad(s) + ' ' +
(h >= 12 ? 'PM' : 'AM');
}
window.onload = function() {
var clk = document.getElementById('clk');
t = setInterval(time1, 500);
}
<span id="clk"></span>
jQuery doesn't have any Date utilities at all. If you don't use any additional libraries, the usual way is to create a JavaScript Date object and then extract the data from it and format it yourself.
For creating the Date object you can either make sure that your date string in the JSON is in a form that Date understands, which is IETF standard (which is basically RFC 822 section 5). So if you have the chance to change your JSON, that would be easiest. (EDIT: Your format may actually work the way it is.)
If you can't change your JSON, then you'll need to parse the string yourself and get day, mouth, year, hours, minutes and seconds as integers and create the Date object with that.
Once you have your Date object you'll need to extract the data you need and format it:
var myDate = new Date("4 Feb 2011, 19:00:00");
var hours = myDate.getHours();
var am = true;
if (hours > 12) {
am = false;
hours -= 12;
} else (hours == 12) {
am = false;
} else (hours == 0) {
hours = 12;
}
var minutes = myDate.getMinutes();
alert("It is " + hours + " " + (am ? "a.m." : "p.m.") + " and " + minutes + " minutes".);
1) "Squared" instructions for making 24-hours became 12-hours:
var hours24 = new Date().getHours(); // retrieve current hours (in 24 mode)
var dayMode = hours24 < 12 ? "am" : "pm"; // if it's less than 12 then "am"
var hours12 = hours24 <= 12 ? (hours24 == 0 ? 12 : hours24) : hours24 - 12;
// "0" in 24-mode now becames "12 am" in 12-mode – thanks to user #Cristian
document.write(hours12 + " " + dayMode); // printing out the result of code
2) In a single line (same result with slightly different algorythm):
var str12 = (h24 = new Date().getHours()) && (h24 - ((h24 == 0)? -12 : (h24 <= 12)? 0 : 12)) + (h24 < 12 ? " am" : " pm");
Both options return string, like "5 pm" or "10 am" etc.
You can take a look at this. One of the examples says:
var d = new Date(dateString);
Once you have Date object you can fairly easy play with it. You can either call toLocaleDateString, toLocaleTimeString or you can test if getHours is bigger than 12 and then just calculate AM/PM time.
date = date.replace(/[0-9]{1,2}(:[0-9]{2}){2}/, function (time) {
var hms = time.split(':'),
h = +hms[0],
suffix = (h < 12) ? 'am' : 'pm';
hms[0] = h % 12 || 12;
return hms.join(':') + suffix
});
edit: I forgot to deal with 12 o'clock am/pm. Fixed.
var dt = new Date();
var h = dt.getHours(), m = dt.getMinutes();
var thistime = (h > 12) ? (h-12 + ':' + m +' PM') : (h + ':' + m +' AM');
console.log(thistime);
Here is the Demo
function GetTime(date) {
var currentTime = (new Date(date))
var hours = currentTime.getHours()
//Note: before converting into 12 hour format
var suffix = '';
if (hours > 11) {
suffix += "PM";
} else {
suffix += "AM";
}
var minutes = currentTime.getMinutes()
if (minutes < 10) {
minutes = "0" + minutes
}
if (hours > 12) {
hours -= 12;
} else if (hours === 0) {
hours = 12;
}
var time = hours + ":" + minutes + " " + suffix;
return time;
}
Please try with below code
var s = "15 Feb 2015 11.30 a.m";
var times = s.match("((([0-9])|([0-2][0-9])).([0-9][0-9])[\t ]?((a.m|p.m)|(A.M|P.M)))");
var time = "";
if(times != null){
var hour = times[2];
if((times[6] == "p.m" || times[6] == "P.M")){
if(hour < 12){
hour = parseInt(hour) + parseInt(12);
}else if(hour == 12){
hour = "00";
}
}
time = [hour, times[5], "00"].join(":");
}
Thanks
This worked for me!
function main() {
var time = readLine();
var formattedTime = time.replace('AM', ' AM').replace('PM', ' PM');
var separators = [':', ' M'];
var hms = formattedTime.split(new RegExp('[' + separators.join('') + ']'));
if (parseInt(hms[0]) < 12 && hms[3] == 'P')
hms[0] = parseInt(hms[0]) + 12;
else if (parseInt(hms[0]) == 12 && hms[3] == 'A')
hms[0] = '00';
console.log(hms[0] + ':' + hms[1] + ':' + hms[2]);
}
You could try this more generic function:
function to12HourFormat(date = (new Date)) {
return {
hours: ((date.getHours() + 11) % 12 + 1),
minutes: date.getMinutes(),
meridian: (date.getHours() >= 12) ? 'PM' : 'AM',
};
}
Returns a flexible object format.
https://jsbin.com/vexejanovo/edit
I'm a relative newbie, but here's what I came up with for one of my own projects, and it seems to work. There may be simpler ways to do it.
function getTime() {
var nowTimeDate = new Date();
var nowHour = nowTimeDate.getHours();
var nowMinutes = nowTimeDate.getMinutes();
var suffix = nowHour >= 12 ? "pm" : "am";
nowHour = (suffix == "pm" & (nowHour > 12 & nowHour < 24)) ? (nowHour - 12) : nowHour;
nowHour = nowHour == 0 ? 12 : nowHour;
nowMinutes = nowMinutes < 10 ? "0" + nowMinutes : nowMinutes;
var currentTime = nowHour + ":" + nowMinutes + suffix;
document.getElementById("currentTime").innerHTML = currentTime;
}
this is your html code where you are calling function to convert 24 hour time format to 12 hour with am/pm
<pre id="tests" onClick="tConvert('18:00:00')">
test on click 18:00:00
</pre>
<span id="rzlt"></span>
now in js code write this tConvert function as it is
function tConvert (time)
{
// Check correct time format and split into components
time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];
if (time.length > 1)
{ // If time format correct
time = time.slice (1); // Remove full string match value
time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM
time[0] = +time[0] % 12 || 12; // Adjust hours
}
//return time; // return adjusted time or original string
var tel = document.getElementById ('rzlt');
tel.innerHTML= time.join ('');
}
converting 18:00:00 to 6:00:00PM working for me
This function will convert in both directions:
12 to 24 hour or 24 to 12 hour
function toggle24hr(time, onoff){
if(onoff==undefined) onoff = isNaN(time.replace(':',''))//auto-detect format
var pm = time.toString().toLowerCase().indexOf('pm')>-1 //check if 'pm' exists in the time string
time = time.toString().toLowerCase().replace(/[ap]m/,'').split(':') //convert time to an array of numbers
time[0] = Number(time[0])
if(onoff){//convert to 24 hour:
if((pm && time[0]!=12)) time[0] += 12
else if(!pm && time[0]==12) time[0] = '00' //handle midnight
if(String(time[0]).length==1) time[0] = '0'+time[0] //add leading zeros if needed
}else{ //convert to 12 hour:
pm = time[0]>=12
if(!time[0]) time[0]=12 //handle midnight
else if(pm && time[0]!=12) time[0] -= 12
}
return onoff ? time.join(':') : time.join(':')+(pm ? 'pm' : 'am')
}
Here's some examples:
//convert to 24 hour:
toggle24hr('12:00am') //returns 00:00
toggle24hr('2:00pm') //returns 14:00
toggle24hr('8:00am') //returns 08:00
toggle24hr('12:00pm') //returns 12:00
//convert to 12 hour:
toggle24hr('14:00') //returns 2:00pm
toggle24hr('08:00') //returns 8:00am
toggle24hr('12:00') //returns 12:00pm
toggle24hr('00:00') //returns 12:00am
//you can also force a specific format like this:
toggle24hr('14:00',1) //returns 14:00
toggle24hr('14:00',0) //returns 2:00pm
Here you go
var myDate = new Date("February 04, 2011 19:00:00");
var hr = myDate.getHours();
var convHrs = "";
var ampmSwitch = "";
ampmSwitch = (hr > 12)? "PM":"AM";
convHrs = (hr >12)? hr-12:hr;
// Build back the Date / time using getMonth/ getFullYear and getDate and other functions on the myDate object. Enclose it inside a func and there you got the working 12 hrs converter ;)
And here's the converter func for yas ;) Happy coding!!
function convertTo12Hrs(yourDateTime){
var myDate = new Date(yourDateTime);
var dtObject = new Object();
var monthsCollection = {0:"January", 1:"February",2:"March",3:"April",4:"May",5:"June",6:"July",7:"August",8:"September",9:"October",10:"November",11:"December"};
dtObject.year = myDate.getFullYear();
dtObject.month = monthsCollection[myDate.getMonth()];
dtObject.day = (myDate.getDate()<10)?"0"+myDate.getDate():myDate.getDate();
dtObject.minutes = (myDate.getMinutes() < 10)? "0"+myDate.getMinutes():myDate.getMinutes();
dtObject.seconds = (myDate.getSeconds() < 10)? "0"+myDate.getSeconds():myDate.getSeconds();
// Check if hours are greater than 12? Its PM
dtObject.ampmSwitch = (myDate.getHours() > 12)? "PM":"AM";
// Convert the hours
dtObject.hour = (myDate.getHours() > 12)?myDate.getHours()-12:myDate.getHours();
// Add the 0 as prefix if its less than 10
dtObject.hour = (dtObject.hour < 10)? "0"+dtObject.hour:dtObject.hour;
// Format back the string as it was or return the dtObject object or however you like. I am returning the object here
return dtObject;
}
invoke it like
convertTo12Hrs("February 04, 2011 19:00:00"); it will return you the object, which in turn you can use to format back your datetime string as you fancy...
You're going to end up doing alot of string manipulation anyway,
so why not just manipulate the date string itself?
Browsers format the date string differently.
Netscape ::: Fri May 11 2012 20:15:49 GMT-0600 (Mountain Daylight Time)
IE ::: Fri May 11 20:17:33 MDT 2012
so you'll have to check for that.
var D = new Date().toString().split(' ')[(document.all)?3:4];
That will set D equal to the 24-hour HH:MM:SS string. Split that on the
colons, and the first element will be the hours.
var H = new Date().toString().split(' ')[(document.all)?3:4].split(':')[0];
You can convert 24-hour hours into 12-hour hours, but that hasn't
actually been mentioned here. Probably because it's fairly CRAZY
what you're actually doing mathematically when you convert hours
from clocks. In fact, what you're doing is adding 23, mod'ing that
by 12, and adding 1
twelveHour = ((twentyfourHour+23)%12)+1;
So, for example, you could grab the whole time from the date string, mod
the hours, and display all that with the new hours.
var T = new Date().toString().split(' ')[(document.all)?3:4].split(':');
T[0] = (((T[0])+23)%12)+1;
alert(T.join(':'));
With some smart regex, you can probably pull the hours off the HH:MM:SS
part of the date string, and mod them all in the same line. It would be
a ridiculous line because the backreference $1 couldn't be used in
calculations without putting a function in the replace.
Here's how that would look:
var T = new Date().toString().split(' ')[(document.all)?3:4].replace(/(^\d\d)/,function(){return ((parseInt(RegExp.$1)+23)%12)+1} );
Which, as I say, is ridiculous. If you're using a library that CAN perform
calculations on backreferences, the line becomes:
var T = new Date().toString().split(' ')[(document.all)?3:4].replace(/(^\d\d)/, (($1+23)%12)+1);
And that's not actually out of the question as useable code, if you document it well.
That line says:
Make a Date string, break it up on the spaces, get the browser-apropos part,
and replace the first two-digit-number with that number mod'ed.
Point of the story is, the way to convert 24-hour-clock hours to 12-hour-clock hours
is a non-obvious mathematical calculation:
You add 23, mod by 12, then add one more.
Here is a nice little function that worked for me.
function getDisplayDatetime() {
var d = new Date(); var hh = d.getHours(); var mm = d.getMinutes(); var dd = "AM"; var h = hh;
if (mm.toString().length == 1) {
mm = "0" + mm;
}
if (h >= 12) {
h = hh - 12;
dd = "PM";
}
if (h == 0) {
h = 12;
}
var Datetime = "Datetime: " + d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getUTCDate() + " " + h + ":" + mm;
return Datetime + " " + dd;
}
I noticed there is already an answer, but I wanted to share my own solution, using pure JavaScript:
function curTime(pm) {
var dt = new Date();
var hr = dt.getHours(), min = dt.getMinutes(), sec = dt.getSeconds();
var time = (pm ? ((hr+11)%12+1) : (hr<10?'0':'')+hr)+":"+(min<10?'0':'')+min+":"+(sec<10?'0':'')+sec+(pm ? (hr>12 ? " PM" : " AM") : "");
return time;
}
You can see it in action at https://jsfiddle.net/j2xk312m/3/ using the following code block:
(function() {
function curTime(pm) {
var dt = new Date();
var hr = dt.getHours(), min = dt.getMinutes(), sec = dt.getSeconds();
var time = (pm ? ((hr+11)%12+1) : (hr<10?'0':'')+hr)+":"+(min<10?'0':'')+min+":"+(sec<10?'0':'')+sec+(pm ? (hr>12 ? " PM" : " AM") : "");
return time;
}
alert("12-hour Format: "+curTime(true)+"\n24-hour Format: "+curTime(false));
})();
This way you have more control over the output - i.e - if you wanted the time format to be '4:30 pm' instead of '04:30 P.M.' - you can convert to whatever format you decide you want - and change it later too. Instead of being constrained to some old method that does not allow any flexibility.
and you only need to convert the first 2 digits as the minute and seconds digits are the same in 24 hour time or 12 hour time.
var my_time_conversion_arr = {'01':"01", '02':"02", '03':"03", '04':"04", '05':"05", '06':"06", '07':"07", '08':"08", '09':"09", '10':"10", '11':"11", '12': "12", '13': "1", '14': "2", '15': "3", '16': "4", '17': "5", '18': "6", '19': "7", '20': "8", '21': "9", '22': "10", '23': "11", '00':"12"};
var AM_or_PM = "";
var twenty_four_hour_time = "16:30";
var twenty_four_hour_time_arr = twenty_four_hour_time.split(":");
var twenty_four_hour_time_first_two_digits = twenty_four_hour_time_arr[0];
var first_two_twelve_hour_digits_converted = my_time_conversion_arr[twenty_four_hour_time_first_two_digits];
var time_strng_to_nmbr = parseInt(twenty_four_hour_time_first_two_digits);
if(time_strng_to_nmbr >12){
//alert("GREATER THAN 12");
AM_or_PM = "pm";
}else{
AM_or_PM = "am";
}
var twelve_hour_time_conversion = first_two_twelve_hour_digits_converted+":"+twenty_four_hour_time_arr[1]+" "+AM_or_PM;

Categories