Is there any way i could convert a 12hour time format into a 24 hour format in JS?
I'm not that good with JavaScript at all so still surprised i could manage to get even this far.
What i'm trying to do is convert time from 12 hour to 24 hour so i can do comparison, like if endDate is greater than startDate, but what i cant understand is how to convert the 12 hour format i receive to a valid 24hour format.
$('#de_endTime').bind('blur', function()
{
sDate = $('#de_startDate').val();
startTime = $('#de_startTime').val();
endTime = $('#de_endTime').val();
if (startTime == ""){
alert("First input the start time");
$('#de_startTime').focus();
}
dSplit = sDate.split("-");
dYear = dSplit[0];
dMonth = dSplit[1] - 1;
dDay = dSplit[2];
stSplit = startTime.split(":");
stHour = stSplit[0];
stMin = stSplit[1].split(" ")[0];
stAmPm = stSplit[1].split(" ")[1];
etSplit = endTime.split(":");
etHour = etSplit[0];
etMin = etSplit[1].split(" ")[0];
etAmPm = etSplit[1].split(" ")[1];
fullStartDate = getDateObject(dYear, dMonth, dDay, stHour, stMin);
fullEndDate = getDateObject(dYear, dMonth, dDay, etHour, etMin);
if (fullStartDate - fullEndDate > 0){
alert("Start Time cannot be higher than End Time!");
}
});
Here is the getDateObject() function
function getDateObject(year, month, day, hours, minutes) {
var newDate = new Date();
newDate.setFullYear(year);
newDate.setMonth(month);
newDate.setDate(day);
newDate.setHours(hours);
newDate.setMinutes(minutes);
newDate.setSeconds(0);
newDate.setMilliseconds(0);
return newDate;
}
I'm not sure if i've provided enough detail, but please let me know if didnt :)
Thanks :)
[ EDIT ]
The new code, which seems to be outputting everything fine so far :)
$('#de_endTime').bind('blur', function()
{
sDate = $('#de_startDate').val();
startTime = $('#de_startTime').val();
endTime = $('#de_endTime').val();
if (startTime == ""){
alert("First input the start time");
$('#de_startTime').focus();
}
dSplit = sDate.split("-");
dYear = dSplit[0];
dMonth = dSplit[1];
dDay = dSplit[2];
fullIsoDate = dMonth + "/" + dDay + "/" + dYear;
//alert(fullIsoDate);
var fullStartDate = new Date(startTime + ' ' + fullIsoDate);
var fullEndDate = new Date(endTime + ' ' + fullIsoDate);
alert(fullStartDate);
if (fullStartDate - fullEndDate > 0){
alert("Start Time cannot be higher than End Time!");
}
alert(fullEndDate > fullStartDate)
});
date objects can be compared directly, and do not care about 12/24 hour format, so just put your times in two date objects and compare.
var dateOne = new Date('1:00 PM 1/1/1900');
var dateTwo = new Date('13:01 1/1/1900');
if(dateOne < dateTwo)
{
alert('DateOne is before DateTwo');
} else {
alert('DateOne is after DateTwo');
}
You will get a alert box that says DateOne is before DateTwo
I had been looking everywhere for just something SIMPLE to convert a time from 24-hour format to 12, or vice versa. Literally everything out there was only dealing with dates, or time and dates. So I made a simple time convertor and figured it anyone else needs one here it is (based off of the first example's split methods).
//usage timeConvert("12:01 PM","24") results 12:01:00
//OR timeConvert("12:01:00","12") results 12:01 PM
function timeConvert(time,twelvOrTwen){
var stSplit = time.split(":");
var stHour = stSplit[0];
var stMin = stSplit[1].split(" ")[0];
var stAmPm = stSplit[1].split(" ")[1];
var newhr = 0;
var ampm = '';
var newtime = '';
// alert("hour:"+stHour+"\nmin:"+stMin+"\nampm:"+stAmPm); //see current values
if (twelvOrTwen == "12") {
if (stHour == 12){
ampm = "PM";
newhr = 12;
}
else if (stHour == 00){;
ampm = "AM";
newmin = stMin;
newhr = 12;
}
else if (stHour > 12){
newhr = stHour - 12;
ampm = "PM";
}
else {
newhr = stHour;
ampm = "AM";
}
newtime = newhr+":"+stMin+" "+ampm;
}
else if (twelvOrTwen == "24"){
if ((stAmPm == "pm") || (stAmPm == "PM")){
if (stHour < 12) {
newhr = (stHour*1)+(1*12); //goes to 13
}
else { //means is 12:30 PM
newhr = 12;
}
}
newtime = newhr+":"+stMin+":"+"00";
}
else {
alert("No Time To Convert Or Didn't Specify 12 or 24");
}
return newtime;
}
Apparently, this question is already old, but I would be pasting my solution to answer the question that your title states. However this must mean that the 12 hour time format must come with a space separating the time and time of the day i.e. (am or pm).
Solution 1:
function convertTimeTo24(time) {
const realTime = time.split(" ");
if (realTime[1].toLowerCase() === "am") {
return realTime[0];
} else {
const timeToReturn = realTime[0].split(":");
const increaseHours = Number(timeToReturn[0]) + 12;
return `${increaseHours}:${timeToReturn[1]}`;
}
}
Related
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/
var timeZone ="CDT"
var startDateTime = "2016-06-15 22:30:00.0";
this.outDate = function()
{
return getJustTime(startDateTime,timeZone);
}
function getJustTime(startDateTime,timeZone)
{
outDt = new Date(startDateTime.replace(/ /g,'T'));
return outDt;
}
**Expected Output**
this.outDate = "10.30 PM CDT";
I have two variables as above with 24 hour datetime string and i want to convert it into 12 hour format date string. What i am missing in the missing?
P.S : I can't use any datetime librarires.
Just write your own. The date object is very helpful.
function am_or_pm (date) {
var date_obj = new Date(date);
var hours = date_obj.getHours();
var morn_or_night;
// I wouldn't do this in production, but this is to make my logic really clear - I would probably use a conditional operator here.
// Handling Midnight
if (hours === 0) {
hours = 12;
morn_or_night = 'AM';
// Handling noon
} else if (hours === 12) {
morn_or_night = 'PM'
} else if (hours > 12) {
hours = hours - 12;
morn_or_night = 'PM';
} else {
morn_or_night = 'AM';
}
return hours.toString()+':'+date_obj.getMinutes()+' '+morn_or_night;
}
var timeZone ="CDT"
var startDateTime = "2016-06-15 22:30:00.0";
var slot='AM';
var a = startDateTime.split(" ");
var b = a[0].split("-");
var c = a[1].split(":");
if(c[0]>12){
slot='PM';
c[0] = c[0] - 12;
}
var date = c[0]+'.'+c[1]+' '+slot+' '+timeZone ;
console.log(date);
I have a string like this 3:35 PM - 5:25 PM. I am trying to write two functions getStartTime(times) and getEndTime(times) which return the start and end times in 24 hour clock format, i.e. in the above case it would return 15:35 and 17:25. So far I have a working getStartTime(times):
function getStartTime(times){
var spaceSplit=times.split(" ");
var colonSplit=times.split(":");
if(s.search("PM")!=-1&&colonSplit[0]<12){
return String(Number(colonSplit[0])+12)+":"+colonSplit[1].substring(0,2);
}
return spaceSplit[0];
}
However, it is ugly and I am not sure how to do the getEndTime(times). Anyone know an elegant way to do both of these functions? Note that the string will always be in that format (although the hours could be two digits).
function getStartTime(times)
{
var start_time = times.split("-")[0].trim();
var res = start_time.split(" ");
var hh = res[0].split(":")[0];
var mm = res[0].split(":")[1];
if( res[1]== "PM" && hh !="12")
{
hh = +hh + 12;
}
else if(hh==12 && res[1] == "AM")
{
hh = "00";
}
return(hh+":"+mm);
}
function getEndTime(times)
{
var end_time = times.split("-")[0].trim();
var res = end_time.split(" ");
var hh = res[0].split(":")[0];
var mm = res[0].split(":")[1];
if( res[1]== "PM" && hh !="12")
{
hh = +hh + 12;
}
else if(hh==12 && res[1] == "AM")
{
hh = "00";
}
return(hh+":"+mm);
}
This can easily be done with regex:
var t = '3:35 PM - 5:25 PM';
console.log(getTimes(t));
function getTimes(timeString) {
var matches = /^([1-9]|1[0-2])(:[0-5][0-9]) ([AP])M - ([1-9]|1[0-2])(:[0-5][0-9]) ([AP])M$/.exec(timeString);
return [parseInt(matches[1]) % 12 + (matches[3] == 'A' ? 0 : 12) + matches[2],
parseInt(matches[4]) % 12 + (matches[6] == 'A' ? 0 : 12) + matches[5]];
}
http://jsfiddle.net/p5xzwuch/1/
Edit: You can match the : in the same group with the minutes, then you don't have to insert it manually ("corrected"). It just shows another way, if you don't know the number of whitespaces then you might have to modify a little and it is probably not the fastest way. The good thing about using regex is you can first see if it matches and only then return the result as shown, otherwise you can handle the error.
I am looking to show an estimated delivery date on the product page for each delivery option we have. I have read through the code in Shopify Variants by Steph Sharp which would work brilliantly except we would need it to be fixed to the current day up until 3pm and then switch to the next working day after 3pm. (Basically taking away the option for the customer to choose the dispatch day.)
I can’t quite get it to work by butchering this code into our template. This is what I have butchered together which seems to work okay but rather than have MON, TUE, WED, … I want to set them as the future dates. Any advice?
EDIT: Also I heard Palec is after using a timer code with this code too. So I will add that in.
<script language="JavaScript">
function day(a) {
var date = new Date();
var days = ["Mon","Tue","Wed","Thur","Fri","Mon","Tue","Wed","Thur","Fri","Mon","Tue","Wed","Thur","Fri"];
var today = date.getDay();
if (today == 1) today = 0; //Monday
if (today == 2) today = 1; //Tuesday
if (today == 3) today = 2; //Wednesday
if (today == 4) today = 4; //Thursday
if (today == 5) today = 5; //Friday
if (today == 6) today = -1; //Saturday Moved To Monday
if (today == 0) today = -1; //Sunday Moved To Monday
h = date.getHours();
if (h <= 9) h = "0" + h;
time = h;
if (time > 15) today++;
var expected = today + a;
var main = days[expected];
document.write('STANDARD DELIVERY ESTIMATE: ');
document.write(main);
}
</script>
<body>
<script language="JavaScript">
day(1)
</script>
I would try something like this:
function day(a) {
var date = new Date();
var hours = date.getHours();
// If after 3pm, add 1 day
if(hours > 15) a++;
var expectedDeliveryDate = addWeekdays(date, a);
document.write(expectedDeliveryDate.toDateString() + ' with Standard Delivery');
}
function addWeekdays(fromDate, days) {
var count = 0;
while (count < days) {
fromDate.setDate(fromDate.getDate() + 1);
if (fromDate.getDay() != 0 && fromDate.getDay() != 6) // Skip weekends
count++;
}
return fromDate;
}
(The code in the addWeekdays function is from this answer on Stack Overflow.)
This code just displays the day name (like the code in your question), but you can format expectedDeliveryDate however you want.
EDIT: I updated my code to use expectedDeliveryDate.toDateString() as specified in the comments. Note that you no longer need the days array or expectedDeliveryDay variable. (You've still got them in your answer but they're not being used.)
This is my final code, based on Steph Sharp’s answer.
function day(a) {
var date = new Date();
var hours = date.getHours();
// If after 3pm, add 1 day
if (hours >= 15) a++;
var expectedDeliveryDate = addWeekdays(date, a);
document.write(expectedDeliveryDate.toDateString() + ' with Standard Delivery');
}
function addWeekdays(fromDate, days) {
var count = 0;
while (count < days) {
fromDate.setDate(fromDate.getDate() + 1);
if (fromDate.getDay() != 0 && fromDate.getDay() != 6) // Skip weekends
count++;
}
return fromDate;
}
Also added a timer:
function ShowTime() {
var now = new Date();
var hrs = 15 - now.getHours();
if (hrs < 0) hrs += 24;
var mins = 60 - now.getMinutes();
var secs = 60 - now.getSeconds();
timeLeft = "" + hrs + ' hours ' + mins + ' minutes ' + secs + ' seconds';
$("#countdown").html(timeLeft);
}
var countdown = setInterval(ShowTime, 1000);
function StopTime() {
clearInterval(countdown);
}
I want to adding a time with current time using javascript....
Easiest to set an example...
e.g.
In the admin section set the "Minimum Hours Booking Notice" as 12 hours ($minHours = 12)
The time now is 10:30 on 26th July 2011
I want to book a vehicle for today at 17:00
BUT 10:30 + $minHours < 17:00
THEREFORE I CANNOT make the booking. Then I should be notified by a popup/ notice onscreen and the booking should not be allowed.
PHP Code for this.....
$hour1 = $this->input->post('time1');
$sec1 = $this->input->post('sec1');
$act = $hour1 . ':' . $sec1;
$min_hr = $this->input->post('min_hr');
$current_time = date("H:i");
$new_date = date('d');
$exe = explode(':', $current_time);
$new_time = $exe['0'] + $min_hr;
if ($new_time > 24) {
$new_time = $new_time - 24;
$new_date = date('d') + 1;
} else {
$new_time = $new_time;
$new_date = date('d');
}
if($date1 > $new_date){
if($hour1 > $new_time){
redirect('mesage');
} elseif ($hour1 == $new_time) {
if($sec1 <= $exe['1']){
redirect('mesage');
}
}
} elseif ($date1 == $new_date) {
if($hour1 < $new_time){
redirect('mesage');
} elseif ($hour1 == $new_time) {
if($sec1 <= $exe['1']){
redirect('mesage');
}
}
}
Please help....
a LOT of issues with your code. I am posting an answer for formatting and to understand the code
This is not needed
} else {
$new_time = $new_time;
$new_date = date('d');
}
what is date1?
Why do you have sec1 when you obviously mean minutes
Where will the parameters for the script come from?
Here is your php in JS
var hour1 = qs('time1'); // qs is some function that for example uses the query string
var min1 = qs('sec1'); // you do mean minutes, no?
var act = hour1 + ':' + min1;
var min_hr = qs('min_hr');
var new_date = new Date();
var hh = new_date.getHours();
var mm = new_date.getMinutes();
var ss = new_date.getSeconds();
var new_time = hh + parseInt(min_hr);
if (new_time > 24) {
new_time = new_time - 24;
new_date.setDate(new_date.getDate()+1);
}
if(date1.getTime() > new_date.getTime(){ // where did date1 come from?
if(hour1 > new_time){
alert("message")
}
else if (hour1 == new_time && min1 <= mm){
alert("message")
}
}
else if (date1.getTime() == new_date.getTime() {
if(hour1 < new_time){
alert('message');
}
else if (hour1 == new_time && min1 <= mm){
alert('mesage');
}
}
For javascript datetime manupilation I would recommend Datejs library.
It allows a flexible datetime addition and subtraction, ie.:
// Get today's date
Date.today();
// Add 5 days to today
Date.today().add(5).days();
// Get Friday of this week
Date.friday();
// Get March of this year
Date.march();
// Is today Friday?
Date.today().is().friday(); // true|false
// What day is it?
Date.today().getDayName();