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();
Related
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);
Ok so what the title says. I am doing this on a server, so I get the server's time using some PHP code. The problem is that it is a time frame without exact round hour values. Should I use nested if else statements?
var serverTimestampMillis = <?php print time() * 1000 ?>;
var checkInterval = 1000;
var checkTime = function () {
serverTimestampMillis += checkInterval;
var now = new Date(serverTimestampMillis);
var timeDiv = document.getElementById('timeDiv');
var messageDiv = document.getElementById('messageDiv');
timeDiv.innerHTML = now.toString();
var dayOfWeek = now.getDay(); // 0 = Sunday, 1 = Monday, ... 6 = Saturday
var hour = now.getHours(); // 0 = 12am, 1 = 1am, ... 18 = 6pm
var minutes = now.getMinutes();
// check if it's Monday to Thursday between 8:30am and 6:30pm
// this is where I don't know how to check 8:30
if (dayOfWeek > 0 && dayOfWeek < 5 && hour > 8 && hour < 18) {
messageDiv.innerHTML = 'Yes, we are open!';
messageDiv.className='open';
}
else {
messageDiv.innerHTML = 'Sorry, we\'re closed!';
messageDiv.className='closed';
}
};
// check the time every 1000 milliseconds
setInterval(checkTime, checkInterval);
checkTime();
thank you in advance, and sorry for being a noob
Compare between two dates using a helper function:
function createDateTime(time) {
var splitted = time.split(':');
if (splitted.length != 2) return undefined;
var date = new Date();
date.setHours(parseInt(splitted[0], 10));
date.setMinutes(parseInt(splitted[1], 10));
date.setSeconds(0);
return date;
}
var startDate = createDateTime("8:30");
var endDate = createDateTime("17:30");
var now = new Date();
var isBetween = startDate <= now && now <= endDate;
console.log(isBetween);
JSFIDDLE.
You can just nest your statements, like you said (to make it easier to read), and then check the specific edge cases (8:30-9 and 18:00-18:30).
if (dayOfWeek > 0 && dayOfWeek < 5) {
if ((hour > 8 && hour < 18) ||
(hour == 8 && minutes >= 30) ||
(hour == 18 && minutes <= 30)) {
messageDiv.innerHTML = 'Yes, we are open!';
messageDiv.className='open';
}
}
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 am trying to exclude weekends in my JavaScript code. I use moment.js and having difficulty choosing the right variable for 'days'.
So far I have thought that I need to exclude day 6 (saturday) and day 0 (sunday) by changing the weekday variable to count from day 1 to day 5 only. But not sure how it changes.
My jsfiddle is shown here: FIDDLE
HTML:
<div id="myContent">
<input type="radio" value="types" class="syncTypes" name="syncTypes"> <td><label for="xshipping.xshipping1">Free Shipping: (<span id="fsv1" value="5">5</span> to <span id="fsv2" value="10">10</span> working days)</label> </td><br>
<div id="contacts" style="display:none;border:1px #666 solid;padding:3px;top:15px;position:relative;margin-bottom:25px;">
Contacts
</div>
<input type="radio" value="groups" class="syncTypes" name="syncTypes"> <td><label for="xshipping.xshipping2">Express Shipping: (<span id="esv1" value="3">3</span> to <span id="esv2" value="4">4</span> working days)</label> </td>
<div id="groups" style="display:none;border:1px #666 solid;padding:3px;top:15px;position:relative">
Groups
</div>
</div>
JavaScript:
var a = 5; //Free shipping between a
var b = 10;//and b
var c = 3;//Express shipping between c
var d = 4;//and d
var now = moment();
var f = "Your item will be delivered between " + now.add("days",a).format("Do MMMM") + " and " + now.add("days",b).format("Do MMMM");
var g = "Your item will be delivered between " + now.add("days".c).format("Do MMMM") + " and " + now.add("days",d).format("Do MMMM");
var h = document.getElementById('contacts');
h.innerHTML = g
var i = document.getElementById('groups');
i.innerHTML = f
$(function() {
$types = $('.syncTypes');
$contacts = $('#contacts');
$groups = $('#groups');
$types.change(function() {
$this = $(this).val();
if ($this == "types") {
$groups.slideUp(300);
$contacts.delay(200).slideDown(300);
}
else if ($this == "groups") {
$contacts.slideUp(300);
$groups.delay(200).slideDown(300);
}
});
});
Here you go!
function addWeekdays(date, days) {
date = moment(date); // use a clone
while (days > 0) {
date = date.add(1, 'days');
// decrease "days" only if it's a weekday.
if (date.isoWeekday() !== 6 && date.isoWeekday() !== 7) {
days -= 1;
}
}
return date;
}
You call it like this
var date = addWeekdays(moment(), 5);
I used .isoWeekday instead of .weekday because it doesn't depend on the locale (.weekday(0) can be either Monday or Sunday).
Don't subtract weekdays, i.e addWeekdays(moment(), -3) otherwise this simple function will loop forever!
Updated JSFiddle http://jsfiddle.net/Xt2e6/39/ (using different momentjs cdn)
Those iteration looped solutions would not fit my needs.
They were too slow for large numbers.
So I made my own version:
https://github.com/leonardosantos/momentjs-business
Hope you find it useful.
https://github.com/andruhon/moment-weekday-calc plugin for momentJS might be helpful for similar tasks
It does not solves the exact problem, but it is able to calculate specific weekdays in the range.
Usage:
moment().isoWeekdayCalc({
rangeStart: '1 Apr 2015',
rangeEnd: '31 Mar 2016',
weekdays: [1,2,3,4,5], //weekdays Mon to Fri
exclusions: ['6 Apr 2015','7 Apr 2015'] //public holidays
}) //returns 260 (260 workdays excluding two public holidays)
If you want a pure JavaScript version (not relying on Moment.js) try this...
function addWeekdays(date, days) {
date.setDate(date.getDate());
var counter = 0;
if(days > 0 ){
while (counter < days) {
date.setDate(date.getDate() + 1 ); // Add a day to get the date tomorrow
var check = date.getDay(); // turns the date into a number (0 to 6)
if (check == 0 || check == 6) {
// Do nothing it's the weekend (0=Sun & 6=Sat)
}
else{
counter++; // It's a weekday so increase the counter
}
}
}
return date;
}
You call it like this...
var date = addWeekdays(new Date(), 3);
This function checks each next day to see if it falls on a Saturday (day 6) or Sunday (day 0). If true, the counter is not increased yet the date is increased.
This script is fine for small date increments like a month or less.
I would suggest adding a function to the moment prototype.
Something like this maybe? (untested)
nextWeekday : function () {
var day = this.clone(this);
day = day.add('days', 1);
while(day.weekday() == 0 || day.weekday() == 6){
day = day.add("days", 1);
}
return day;
},
nthWeekday : function (n) {
var day = this.clone(this);
for (var i=0;i<n;i++) {
day = day.nextWeekday();
}
return day;
},
And when you're done and written some tests, send in a pull request for bonus points.
d1 and d2 are moment dates passed as an argument to calculateBusinessDays
calculateBusinessDays(d1, d2) {
const days = d2.diff(d1, "days") + 1;
let newDay: any = d1.toDate(),
workingDays: number = 0,
sundays: number = 0,
saturdays: number = 0;
for (let i = 0; i < days; i++) {
const day = newDay.getDay();
newDay = d1.add(1, "days").toDate();
const isWeekend = ((day % 6) === 0);
if (!isWeekend) {
workingDays++;
}
else {
if (day === 6) saturdays++;
if (day === 0) sundays++;
}
}
console.log("Total Days:", days, "workingDays", workingDays, "saturdays", saturdays, "sundays", sundays);
return workingDays;
}
If you want a version of #acorio's code sample which is performant (using #Isantos's optimisation) and can deal with negative numbers use this:
moment.fn.addWorkdays = function (days) {
// Getting negative / positive increment
var increment = days / Math.abs(days);
// Looping weeks for each full 5 workdays
var date = this.clone().add(Math.floor(Math.abs(days) / 5) * 7 * increment, 'days');
// Account for starting on Saturdays and Sundays
if(date.isoWeekday() === 6) { date.add(-increment, 'days'); }
else if(date.isoWeekday() === 7) { date.add(-2 * increment, 'days'); }
// Adding / removing remaining days in a short loop, jumping over weekends
var remaining = days % 5;
while(remaining != 0) {
date.add(increment, 'days');
if(date.isoWeekday() !== 6 && date.isoWeekday() !== 7)
remaining -= increment;
}
return date;
};
See Fiddle here: http://jsfiddle.net/dain/5xrr79h0/
Edit: now fixed issue adding 5 days to a day initially on a weekend
I know this question was posted long ago, but in case somebody bump on this, here is optimized solution using moment.js:
function getBusinessDays(startDate, endDate){
var startDateMoment = moment(startDate);
var endDateMoment = moment(endDate)
var days = Math.round(startDateMoment.diff(endDateMoment, 'days') - startDateMoment .diff(endDateMoment, 'days') / 7 * 2);
if (endDateMoment.day() === 6) {
days--;
}
if (startDateMoment.day() === 7) {
days--;
}
return days;
}
const calcBusinessDays = (d1, d2) => {
// Calc all days used including last day ( the +1 )
const days = d2.diff(d1, 'days') + 1;
console.log('Days:', days);
// how many full weekends occured in this time span
const weekends = Math.floor( days / 7 );
console.log('Full Weekends:', weekends);
// Subtract all the weekend days
let businessDays = days - ( weekends * 2);
// Special case for weeks less than 7
if( weekends === 0 ){
const cur = d1.clone();
for( let i =0; i < days; i++ ){
if( cur.day() === 0 || cur.day() === 6 ){
businessDays--;
}
cur.add(1, 'days')
}
} else {
// If the last day is a saturday we need to account for it
if (d2.day() === 6 ) {
console.log('Extra weekend day (Saturday)');
businessDays--;
}
// If the first day is a sunday we need to account for it
if (d1.day() === 0) {
console.log('Extra weekend day (Sunday)');
businessDays--;
}
}
console.log('Business days:', businessDays);
return businessDays;
}
This can be done without looping between all dates in between.
// get nb of weekend days
var startDateMonday = startDate.clone().startOf('isoWeek');
var endDateMonday = endDate.clone().startOf('isoWeek');
var nbWeekEndDays = 2 * endDateMonday.diff(startDateMonday, 'days') / 7;
var isoDayStart = startDate.isoWeekday();
if (isoDayStart > 5) // starts during the weekend
{
nbWeekEndDays -= (8 - isoDayStart);
}
var isoDayEnd = endDate.isoWeekday();
if (isoDayEnd > 5) // ends during the weekend
{
nbWeekEndDays += (8 - isoDayEnd);
}
// if we want to also exlcude holidays
var startOfStartDate = startDate.clone().startOf('day');
var nbHolidays = holidays.filter(h => {
return h.isSameOrAfter(startOfStartDate) && h.isSameOrBefore(endDate);
}).length;
var duration = moment.duration(endDate.diff(startDate));
duration = duration.subtract({ days: nbWeekEndDays + nbHolidays });
var nbWorkingDays = Math.floor(duration.asDays()); // get only nb of complete days
I am iterating from start date to end date and only counting days which are weekdays.
const calculateBusinessDays = (start_date, end_date) => {
const d1 = start_date.clone();
let num_days = 0;
while(end_date.diff(d1.add(1, 'days')) > 0) {
if ([0, 6].includes(d1.day())) {
// Don't count the days
} else {
num_days++;
}
}
return num_days;
}
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]}`;
}
}