Date and Time expiration logic not working - javascript

I am trying to check for a expired date and time logic. The time is in 12 hour clock format. I want to check if date is today, then user should not be able to pick expired time. However, if the date selected is tomorrow, then any time can be selected.If date is yesterady, then user should not be able to select the date.
I am trying to do a check in jquery, but not sure how to check. The date is in the format of "MM/DD/YYYY", and the time is in format of "hh:mm a". Expired time of 5 minutes is allowed. I have tried this code:
var targetTime = new Date().setMinutes(-5).valueOf();
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
today = mm + '/' + dd + '/' + yyyy;
if (jQuery('#startDatepicker').find("input").val() == today) {
var currentStartDate = jQuery('#startDatepicker').find("input").val();
var currentStartTime = jQuery('#startTimepicker').find("input").val();
var UserSelectedTime = getAsDate(currentStartDate, currentStartTime).getTime();
if (UserSelectedTime <= targetTime) {
alert("Start Time has expired. Please select a valid Start Time");
}
}
function getAsDate(day, time) {
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if (AMPM == "pm" && hours < 12) hours = hours + 12;
if (AMPM == "am" && hours == 12) hours = hours - 12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if (hours < 10) sHours = "0" + sHours;
if (minutes < 10) sMinutes = "0" + sMinutes;
time = sHours + ":" + sMinutes + ":00";
var d = new Date(day);
var n = d.toISOString().substring(0, 10);
var newDate = new Date(n + "T" + time);
return newDate;
}
If the current date is today and If the current time is 4:00 AM, if the user has selected 3:00 am , then the time has expired, but the alert message is not showing.
How to fix this?
Thanks

Related

Add "am" or "pm" to Specific Time Format Dependent on Time of Day - Javascript

I have the following javaScript which is showing the time in hours and minutes.
Is there a way of having an "am" or "pm" next to the time, dependent on whether it's before or after midday?
var t = new Date();
var time = document.getElementById("time");
time.textContent = t.getHours() + ":" + t.getMinutes();
<h3 class="time-holder">Current UK time: <span id="time">12:00</span></h3>
Answer adapted from here.
var d = new Date();
var hr = d.getHours();
var min = d.getMinutes();
if (min < 10) {
min = "0" + min;
}
var ampm = "am";
if( hr > 12 ) {
hr -= 12;
ampm = "pm";
}
var time = document.getElementById("time");
time.textContent = hr + ":" + min + ampm;
<h3 class="time-holder">Current UK time: <span id="time">12:00</span></h3>
use the "toLocaleTimeString()" method instead of the "getHours()" and "getMinutes()"
for example:
var t = new Date();
var time = document.getElementById("time");
time.textContent = t.toLocaleTimeString('en-US');
source:
https://www.w3schools.com/jsref/jsref_tolocaletimestring.asp

How to convert UTC to CST using Javascript or Jquery

I would like to convert the below time to CST. How can I achieve it using Jquery or Javascript? It should always display as a CST timezone.
var date = new Date();
var dd = date.getDate();
var mm = date.getMonth() + 1;
var yy = date.getFullYear();
var hh = date.getHours();
var minutes = date.getMinutes();
if (minutes < 10)
minutes = "0" + minutes;
var suffix = "AM";
if (hh >= 12) {
suffix = "PM";
hh = hh - 12;
}
if (hh == 0) {
hh = 12;
}
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var valsss = (mm) + "/" + dd + "/" + yy + hh + " " + ":" + minutes + " " + suffix;
$("#printDate").text(valsss);
<p id= "#printDate"></p>
Please check this below like can convert
d = new Date();
localTime = d.getTime();
localOffset = d.getTimezoneOffset() * 60000;
utc = localTime + localOffset;
offset = -5;
cst = utc + (3600000 * offset);
nd = new Date(cst);
newdate = (nd.toLocaleString());
$('#printDate').text(newdate + ' CST');
You have to consider that the browser will change the displayed date to the user's timezone. I wrote this to grab a date in a kendo grid by a class on a td and set it to CST. In this case the server is in CST and I wanted the time say 12:00 to display as 12:00 for a user in MST not as 11:00 in MST. Hope it helps...
Checks User / Browser's timezone offset.
Get difference in hours from server timezone offset.
Looks at a column on the Kendo Grid with class .dbDate.
Grabs the grid date (displayedTime).
Uses Moment.js to Convert (convertedTime) it based on the difference (diff)
in hours we pass it.
Formats convertedTime to the desired format i.e. 02/08/18 23:57.
Passes the Grid back the updated date and time.
Must Run Last on load.
function dateOffset() {
var date = new Date();
var offset;
var diff;
offset = date.getTimezoneOffset()
if (offset > 360) { //360 = CST
diff = +(offset - 360) / 60
} else if (offset < 360) {
diff = -(360 - offset) / 60
} else {
diff = 0
}
$(".dbDate").each(function (i) {
var grid = $('#Grid').data('kendoGrid');
var displayedTime = grid.dataSource.data()[i].TicketDateTime
var convertedTime = new moment(displayedTime).add(diff, 'hours').toDate();
var originalTime = moment(convertedTime).format("MM/DD/YY HH:mm");
i + 1
$(this).html(originalTime)
})
}

Why does the date not adjust to the time set by UTC?

When printing the time for the clocks, a similar code works and adjusts for the timezone selected, but this does not work for printing the date. Any idea why?
It just displays the UTC default time.
<script>
function cetDT(){
var now = new Date();
var today = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
var day = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();
var anHour = 1000 * 60 * 60;
today = new Date(today.getTime() - anHour * -2);
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
if (hours >= 12){
meridiem = "";
}
else {
meridiem = "";
}
if (minutes<10){
minutes = "0" + minutes;
}
else {
minutes = minutes;
}
if (seconds<10){
seconds = "0" + seconds;
}
else {
seconds = seconds;
}
document.getElementById("cetDT").innerHTML = (day + '/' + (parseFloat (month) + 1) + '/' + year);
}
cetDT();
</script>
You're using now.getUTCDate(), now.getUTCHours() and similar, which will grab the current date and time in UTC.
To get the local equivalent, you're looking for now.getDate(), now.getHours() etc. Note the lack of 'UTC' in the names.
Note that even though you're updating the today variable with today = new Date(today.getTime() - anHour * -2), today is initialed earlier with the UTC times. Thus, getTime() will be relative to UTC.
To resolve this, all you need to do is swap out the UTC times:
function cetDT() {
var now = new Date();
var today = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes(), now.getSeconds());
var day = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();
var anHour = 1000 * 60 * 60;
today = new Date(today.getTime() - anHour * -2);
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
if (hours >= 12) {
meridiem = "";
} else {
meridiem = "";
}
if (minutes < 10) {
minutes = "0" + minutes;
} else {
minutes = minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
} else {
seconds = seconds;
}
document.getElementById("cetDT").innerHTML = (day + '/' + (parseFloat(month) + 1) + '/' + year);
}
cetDT();
Note that there's also several bits of code that are completely redundant, such as else { seconds = seconds; }. You may wish to look into refactoring this code ;)
Hope this helps! :)

JQuery Datepicker - setting MinDate based on current time

I'm using JQuery Datepicker for customers to choose a delivery date. I want to be able to check if the customer is ordering before noon and if so next day delivery is available. If they are ordering after noon, next day delivery is unavailable and so that day is unselectable.
I've got some code to check against the current time but how to I add this value into MinDate in the settings at the top?
Thank you!
<div class="delivery-date">
<p>
<label for="date">Select a date for delivery below:</label>
<input id="date" type="text" name="properties[delivery-date]" readonly="readonly" style="background:white; width:30%" class="required" data-error="Please choose a delivery date." />
</p>
</div>
<script>
jQuery(function() {
jQuery("#date").datepicker( {
// minDate: new Date(((new Date).getTime() + 49 * 60 * 60 * 1000) ),
minDate: checkBeforeNoon,
maxDate: "+2M", // show up to 2 months
dateFormat: 'dd/mm/yy',
beforeShowDay: available_delivery_dates
} );
});
/*========== check time ==========*/
// if time before 12pm, offer next day delivery
function checkBeforeNoon(nextDayDelivery){
var startTime = '12:00 AM';
var endTime = '12:00 PM';
var curr_time = getval();
if (get24Hr(curr_time) > get24Hr(startTime) && get24Hr(curr_time) < get24Hr(endTime)) {
// before 12pm - next day delivery available
var nextDayDelivery = '+1d';
} else {
// after 12pm - next day delivery unavailable
var nextDayDelivery = '+2d';
}
function get24Hr(time){
var hours = Number(time.match(/^(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if(AMPM == "PM" && hours<12) hours = hours+12;
if(AMPM == "AM" && hours==12) hours = hours-12;
var minutes = Number(time.match(/:(\d+)/)[1]);
hours = hours*100+minutes;
console.log(time +" - "+hours);
return hours;
}
function getval() {
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10) minutes = "0" + minutes;
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
var current_time = hours + ":" + minutes + " " + suffix;
return current_time;
}
}
/*========== Make sundays always unavailable ==========*/
function available_delivery_dates(date) {
var sunday = 0; // unavailable for delivery
var mon = 1
var tue = 2;
var wed = 3;
var thu = 4;
var fri = 5;
var sat = 6;
var day_of_week = date.getDay();
var not_sun = day_of_week > 0;
if(not_sun){
var day = date.getDate();
return [true, ''];
}
else{
// all else - do not allow
return [false, ' ', 'Delivery is unavailable on this day'];
}
}
</script>
You already accomplished it. You simply need to add a return to the function that is checking if it is noon. If you want to advise the client that one day shipping is available now, you can do so by adding a log in your function. Here is your code modified:
http://jsfiddle.net/graphicfreedom/L3tz8243/1/
function checkBeforeNoon(nextDayDelivery){
var startTime = '12:00 AM';
var endTime = '12:00 PM';
var curr_time = getval();
if (get24Hr(curr_time) > get24Hr(startTime) && get24Hr(curr_time) < get24Hr(endTime)) {
// before 12pm - next day delivery available
var nextDayDelivery = '+1d';
$("#log").html('Next day delivery available! Order before noon!'); //show response to user
} else {
// after 12pm - next day delivery unavailable
var nextDayDelivery = '+2d';
$("#log").html('Next day delivery NOT available! It is already past noon :('); //show response to user
}
return nextDayDelivery;
}
Also, you can easily separate the functions. It is easier to read, and you can always call a function from a function. Hope this helps!
Remove the var before nextDayDelivery in the if-else block as you would be redeclaring it. Then return nextDayDelivery. Also, a good idea to fix the missing semi-colons in the getVal() method.
function checkBeforeNoon(nextDayDelivery) {
var startTime = '12:00 AM';
var endTime = '12:00 PM';
var curr_time = getval();
if (get24Hr(curr_time) > get24Hr(startTime) && get24Hr(curr_time) < get24Hr(endTime)) {
// before 12pm - next day delivery available
nextDayDelivery = '+1d'; // REMOVE var FROM HERE
} else {
// after 12pm - next day delivery unavailable
nextDayDelivery = '+2d'; // REMOVE var FROM HERE
}
function get24Hr(time) {
var hours = Number(time.match(/^(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if (AMPM == "PM" && hours < 12) hours = hours + 12;
if (AMPM == "AM" && hours == 12) hours = hours - 12;
var minutes = Number(time.match(/:(\d+)/)[1]);
hours = hours * 100 + minutes;
console.log(time + " - " + hours);
return hours;
}
function getval() {
// ADD MISSING SEMI-COLONS ON THE FOLLOWING 3 LINES
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
if (minutes < 10) minutes = "0" + minutes;
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
var current_time = hours + ":" + minutes + " " + suffix;
return current_time;
}
return nextDayDelivery; // ADD RETURN STATEMENT
}

javascript date conversion

I want to take an existing javascript string and convert it javascript timestamp object,
then store as format YYYYMMDDHHMMSS
mystring = "Mon Nov 07 2011 09:20:58 GMT-0500 (Eastern Standard Time)";
var timeObject = new Date(mystring);
// pass in javascript date object, return variations of YYYY-MM-DD HH:MM:SS
function fnFormatDateTime(timeObject)
{
// construct day/month/year
var month = timeObject.getMonth() + 1;
if (month < 10){
month = "0" + month;
}
var day = timeObject.getDate();
if (day < 10){
day = "0" + day;
}
var year = timeObject.getFullYear();
var currentDate = (" " + year + month + day).trim();
var currentDateFormatted = ( year +"-"+ month +"-"+ day);
// construct current time
var hours = timeObject.getHours();
if (hours < 10){
hours = "0" + hours;
}
var minutes = timeObject.getMinutes();
if (minutes < 10){
minutes = "0" + minutes;
}
var seconds = timeObject.getSeconds();
if (seconds < 10){
seconds = "0" + seconds;
}
var currentTime = (hours + minutes + seconds + " ").trim();
var currentTimeFormatted = (hours +":"+ minutes +":"+ seconds);
var retArray = new Array();
retArray[0] = (currentDateFormatted + " " + currentTimeFormatted);
retArray[1] = (currentDate+ " " + currentTime);
retArray[2] = currentDate;
retArray[3] = currentTime;
return retArray;
}

Categories

Resources