Ok I cant get my head round this, ive looked at so many posts on SF but cant figure it out.
I need to campare server time with hardcorded time.
i have try this
var breackfastCutOffTime = "5:30";
var lunchCutOffTime = "10:00";
var dinnerCutOffTime = "17:00";
var serverTime = currentDate.getHours()+ ":" + currentDate.getMinutes();
if(Date.parse(toDay) == Date.parse(selectedDate)){
if(serverTime >= breackfastCutOffTime ){
document.getElementById("breakfast").disabled = true;
}else if(serverTime >= lunchCutOffTime){
document.getElementById("lunch").disabled = true;
}else if(serverTime >= dinnerCutOffTime){
document.getElementById("dinner").disabled = true;
}
}
I know this cant compare because time are in text format.Some one pleace help me to compleate this.
You can write a function which converts Time(hh:mm) in minutes(mm) only. Then you can compare two times and do your operations accordingly.
pseudocode:
function convert(string time) int {
//split the time by ':'
//convert the string hh,mm to int hour,mm
//calculate total minutes
//return total minutes
}
Refer Date Api for more info.
Below is your modified code. I have commented few lines. Modify according to your logic
Fiddler link
//var breackfastCutOffTime = "5:30";
var breackfastCutOffTime = new Date();
breackfastCutOffTime.setHours(5);
breackfastCutOffTime.setMinutes(30);
//var lunchCutOffTime = "10:00";
var lunchCutOffTime = new Date();
lunchCutOffTime.setHours(10);
lunchCutOffTime.setMinutes(00);
//var dinnerCutOffTime = "17:00";
var dinnerCutOffTime = new Date();
dinnerCutOffTime.setHours(17);
dinnerCutOffTime.setMinutes(00)
var serverTime = new Date();
//var serverTime = currentDate.getHours()+ ":" + currentDate.getMinutes();
//if(Date.parse(toDay) == Date.parse(selectedDate)){
if(serverTime >= breackfastCutOffTime ){
console.log("breackfastCutOffTime");
//document.getElementById("breakfast").disabled = true;
}else if(serverTime >= lunchCutOffTime){
//document.getElementById("lunch").disabled = true;
console.log("lunchCutOffTime");
}else if(serverTime >= dinnerCutOffTime){
//document.getElementById("dinner").disabled = true;
console.log("dinnerCutOffTime");
}
//}
Explanation:
Instead of converting the Date format to string i am creating new instance of the date for each cutoff time and setting desired time to that object.
Finally compare the date objects directly.
Note: The Date objects are set according to your timezone.
You can pass the breackfastCutOffTime,lunchCutOffTime and dinnerCutOffTime to the below function and it will return true if they are equal to or greater than current time.
function compareTime(timeToCompare) {
var currentDate = new Date();
var tempDate = new Date();
var timeToCompareArray = timeToCompare.split(":");
tempDate.setHours(timeToCompareArray[0]);
tempDate.setMinutes(timeToCompareArray[1]);
if (tempDate >= currentDate) {
return true;
} else {
return false;
}
}
Related
var startDateTime = '15.04.2019 00:15';
var endDateTime = '17.05.2019 18:35';
var checkDateTime = '16.04.2019 13:15';
function(checkDateTime, startDateTime, endDateTime) {
// need codes to return true or false,.
// check "checkDateTime" is between "startDateTime" to "endDateTime"
}
Try this code:
var startDateTime = getDate('15.04.2019 00:15');
var endDateTime = getDate('17.05.2019 18:35');
var checkDateTime = getDate('16.04.2019 13:15');
function isBetween(checkDateTime, startDateTime, endDateTime) {
return (checkDateTime >= startDateTime && checkDateTime <= endDateTime);
}
function toDate(str){
var [ dd, MM, yyyy, hh, mm ] = str.split(/[. :]/g);
return new Date(`${MM}/${dd}/${yyyy} ${hh}:${mm}`);
}
console.log(isBetween(checkDate,startDate,endDate));
To compare it one time falls between a time interval on the same day use: -
var startTime = "00:35";
var endTime = "18:15";
var checkTime = "13:00";
function getMinutes(timeString){
let [hh, mm] = timeString.split(":");
return parseInt(hh)*60 + parseInt(mm);
}
function isTimeBetween(checkTime,startTime,endTime){
checkTime = getMinutes(checkTime);
return (checkTime >= getMinutes(startTime) && checkTime <= getMinutes(endTime));
}
console.log(isTimeBetween(checkTime,startTime,endTime));
You can use new Date().getTime() to get the number of milliseconds since the Unix Epoch. So that you can compared the date/time with the result from this function. You can do sth like that:
return new Date(startDateTime).getTime() <= new Date(checkDateTime).getTime() <= new Date(endDateTime).getTime();
Check this out:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime
I would suggest to check if your checkDateTime is greater than your startDateTime and less then endDateTime.
function checkDateTime(checkDateTime, startDateTime, endDateTime) {
return (new Date(startDateTime) >= new Date(checkDateTime))
&& (new Date(checkDateTime) <= new Date(endDateTime));
}
Here is yet another option which adds the method directly to the Date prototype:
var startDateTime = new Date('04/15/2019 00:15');
var endDateTime = new Date('05/17/2019 18:35');
var checkDateTime = new Date('04/16/2019 13:15');
var outOfRangeDate_EARLY = new Date('01/16/2019 13:15');
var outOfRangeDate_LATE = new Date('06/16/2019 13:15');
Date.prototype.inRange = function(startDate, endDate){
var this_ms = this.getTime();
return ( this_ms >= startDate.getTime() && this_ms <= endDate.getTime() )
}
/* Tests */
console.log('expected: true', 'actual:', checkDateTime.inRange(startDateTime, endDateTime))
console.log('expected: false', 'actual:', outOfRangeDate_EARLY.inRange(startDateTime, endDateTime))
console.log('expected: false', 'actual:', outOfRangeDate_LATE.inRange(startDateTime, endDateTime))
This way, with any date you have var someDate, you can just call someDate.inRange(startDate, endDate). Sometimes, however, messing with the native prototypes can come back to haunt you if not careful. If so, having a separate function as answered by the others is very good.
Lastly, it's very important that the date strings are formatted properly before creating the Date objects, otherwise you'll encounter Invalid Date a lot. I hope this helps.
I'm using cleandersonlobo:date-picker-materialize package to input the date and I want to display an alert("expired") if the input date is less than the current date.
var $strDate = $(".pmt-date").val();
var $dtDate = $.datepicker.parseDate("mm/dd/yy", $strDate);
var $strToday = $.datepicker.formatDate('mm/dd/yy', new Date());
var $tDate = $.datepicker.parseDate('mm/dd/yy', $strToday);
if ($dtDate < new Date()) {
$('#myModal1').modal('hide');
alert("Job expired");
}
Try following code,
var $strDate = $(".pmt-date").val();
var $dtDate = $.datepicker.parseDate("mm/dd/yy", $strDate);
var $strToday = $.datepicker.formatDate('mm/dd/yy', new Date());
var $tDate = $.datepicker.parseDate('mm/dd/yy', $strToday);
if ($dtDate < $strToday ) {
$('#myModal1').modal('hide');
alert("Job expired");
}
A toMidnight function that sets the time of a date to midnight and by doing so removes time as a factor for your comparison:
function toMidnight(date) {
var midnight = arguments.length > 0 ? new Date(date) : new Date();
midnight.setHours(0);
midnight.setMinutes(0);
midnight.setSeconds(0);
midnight.setMilliseconds(0);
return midnight;
}
Then you can compare your date like this:
toMidnight($dtDate) < toMidnight()
I am trying to work with date to getting now is sunset or sunrise.
Since im not sure how to do with If Else statement about Date
I got data when is sunset and when is sunrise.
But was wondering how to do condition if current date is sunset or sunrise with +-15 minutes
Example :
Current date : 2015-12-17T17:45:00 (or between 17:45 to 18:15)
Sunset : 2015-12-17T18:00:00
Rusult = Sunset (because +-15 minutes)
Here is my code so far :
var SunData = {'set':'2015-12-17T09:14:56', 'rise':'2015-12-17T15:10:52'};
var date = new Date();
date = date.getTime();
var sun_rise = new Date(SunData['rise']);
sun_rise = sun_rise.getTime();
var sun_set = new Date(SunData['set']);
sun_set = sun_set.getTime();
var sunRiseSetDiff = 900000; // 15 minutes
// Here
var result;
if(false) {
result = 'sun-rise';
} else if (false) {
result = 'sun-set';
} else {
result = 'none';
}
https://jsfiddle.net/gd1s1o0y/
Can you help me about If Else statement ? Thanks
Do you mean
var result = 'none';
if(Math.abs(date - sun_rise) <= sunRiseSetDiff) {
result = 'sun-rise';
}
else if(Math.abs(date - sun_set) <= sunRiseSetDiff) {
result = 'sun-set';
}
Fiddle
Check this fiddle
var SunData = {'set':'2015-12-17T09:14:56', 'rise':'2015-12-17T15:10:52'};
var date = new Date();
date = date.getTime();
var sun_rise = new Date(SunData['rise']);
sun_rise = sun_rise.getTime();
var sun_set = new Date(SunData['set']);
sun_set = sun_set.getTime();
var sunRiseSetDiff = 900000; // 15 minutes
// Here
var sunsetResult = Math.abs( date - sun_set ) > sunRiseSetDiff ? false: true;
var sunriseResult = Math.abs( date - sun_rise ) > sunRiseSetDiff ? false: true;
if(sunriseResult) {
result = 'sun-rise';
} else if (sunsetResult) {
result = 'sun-rise';
} else {
result = 'none';
}
alert(result);
Just a re-write of your function with comments.
// Always parse date strings manually, you can use a library if you want
// but a bespoke function is pretty simple if the format is guaranteed
// and is a valid date
function qParse(s) {
var b = s.split(/\D/);
return new Date(b[0], b[1]-1, b[2], b[3]||0, b[4]||0, b[5]||0, b[6]||0);
}
// The OP seemed to have sunrise and sunset transposed
var sunData = {'rise':'2015-12-17T09:14:56', 'set':'2015-12-17T15:10:52'};
// There is no need for getTime, date objects can be used in simple
// arithmetic directly
var now = new Date();
var buffer = 9e5; // 15 mintues
// Initialise result to a default string
var result = 'Not near sunrise or sunset';
// Change value if near sunset
if (Math.abs(now - qParse(sunData.set)) <= buffer) {
result = "Close to sunset";
// Otherwise, change value if near sunrise
} else if (Math.abs(now - qParse(sunData.rise)) <= buffer) {
result = "Close to sunrise";
}
// Show result
document.write(result);
Hi i am trying to do a IF statement which allows the current date to be compared to the input date.. if the input date is below the current date it will be false.
I have got the date passing through my variable but it only stores the number so for example it compares day 9 to another day, which is not very reliable. I want the variable to take in the month and the year as well, meaning it can compare the ENTIRE DATE.
If there is a better way let me know.
Here is my code
if (this.element.find('#visitdate').length > 0) {
var dateParts = $('#visitdate').val().split('/');
var check = new Date(dateParts[2], dateParts[1], dateParts[0], 0,0,0,0).getDate();
var today = new Date().getDate;
if (check < today) {
_errMsg = "Please enter a furture visit date";
return false;
} else {
return true;
}
}
Your line for today's date contains an error:
var today = new Date().getDate;
should be
var today = new Date().getDate();
format as mm/dd/yyyy
var from = '08/19/2013 00:00'
var to = '08/12/2013 00:00 '
var today = new Date().getDate();
function isFromBiggerThanTo(dtmfrom, dtmto){
var from = new Date(dtmfrom).getTime();
var to = new Date(dtmto).getTime() ;
return from >= to ;
}
or using below
var x = new Date('2013-05-23');
var y = new Date('2013-05-23');
and compare
You can try this - it's working fine in my project -
Step 1
First Create javascript function as below.
Date.prototype.DaysBetween = function () {
var intMilDay = 24 * 60 * 60 * 1000;
var intMilDif = arguments[0] - this;
var intDays = Math.floor(intMilDif / intMilDay);
if (intDays.toLocaleString() == "NaN") {
return 0;
}
else {
return intDays + 1;
}
}
Step 2
-
var check = new Date(dateParts[2], dateParts[1], dateParts[0], 0,0,0,0).getDate();
var today = new Date().getDate;
var dateDiff = check .DaysBetween(today);
// it will return integer value (difference between two dates )
if(dateDiff > 0 ){ alert('Your message.......');}
You can have this much easier.
You dont need to check with getDate() property you can just compare 2 dates.
And also is not needed to initialize with hours, minutes and seconds the Date, you only need year, month and date.
Here you have your example simplified
var dateParts = $('#visitdate').val().split('/');
var check = new Date(dateParts[2], dateParts[1], dateParts[0]);
var today = new Date();
if (check < today) {
return false;
} else {
return true;
}
http://jsfiddle.net/wns3LkLv/
Try this:
var user="09/09/2014/5/30";
var arrdt= user.split("/");
var userdt = new Date(arrdt[2], arrdt[1] - 1, arrdt[0],arrdt[3],arrdt[4]);
var currdt = new Date();
if (userdt < currdt) {
alert("userdate is before current date"); //do something
}else{
alert("userdate is after current date"); //do something
}
Thanks for all your answers guys i have fixed it.
I used the getTime function instead of getDate.
Then the check variable had to have a -1 assigned to the month as it was going 1 month to high.
var check = new Date(dateParts[2], dateParts[1]-1, dateParts[0], 0,0,0,0).getTime();
Cheers
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]}`;
}
}