I know its a bit silly question, but I actually wanted to know how can I retrieve the year value for a date that I already have without using the "Split" function. I can achieve it with the help of the "split" function. Below is the code that I used in jquery.
outputJSon = JSON.parse($('#' + Datepicker_id).val());
var currentYear = parseInt(CalculateYearfromString($('#' + currentActivityCalendarId).parents('.service-timeline').find('.membership-year .period').text()));
if (currentYear === undefined && $.trim(currentYear) === "")
currentYear = new Date().getFullYear();
if (parseInt(outputJSon["Date"].split('/')[0]) === currentYear)
outputDate = outputJSon["Date"];
else
outputDate = outputJSon["Date"].replace(outputJSon["Date"].split('/')[0], currentYear)
outputDateType = outputJSon["DateType"];
In the above code, I am retrieving the date value in a JSON format which returns Date eg. 2016/05/26 and DateType eg. Day.
I am fetching the current year that I have selected and then checking if currentYear value is equal to the year that I have in the outputJSon["Date"]. If there is a match, then I am replacing the [0] value of the outputJSon["Date"] with the currentYear, with the help of replace function. This works as expected and no error is encountered.
I just want to be sure that if the date format changes(from 2016/05/26 to 26/05/2016)**then the split function that I have written will retrieve wrong value. How can I avoid this. Shall I remove **split function and think of something else?
Any help is appreciated.
Thanks,
Totally unsexy, but what's wrong with indexOf?
if (outputJSon["Date"].indexOf(currentYear) != -1) {
// currentYear is in the string somewhere
}
Note also that in the original, there is no need for parseInt:
outputJSon["Date"].split('/')[0] == currentYear
is sufficient (and less to type).
Also, parseInt will never return undefined, so:
currentYear === undefined
will always be false and so:
if (currentYear === undefined && $.trim(currentYear) === "")
will never be true and the assignment:
currentYear = new Date().getFullYear();
will never execute.
I would also seriously question the use of:
outputJSon = JSON.parse($('#' + Datepicker_id).val());
The use of JSON.parse seems entirely gratuitous, you already have a string returned by $('#' + Datepicker_id).val().
You can check the length to make sure it is a valid year number.
currentYear2 = outputJSon["Date"].split('/');
currentYear2 = (currentYear2[0].length === 4) ? currentYear2[0] : currentYear2[2];
Is there any issues when you simply do
outputDate = new Date(outputJSon["Date"]).getFullYear();
You can try something like this:
JSFiddle.
Code
function getYear() {
var input = $("#dpDate").val();
var cdate = getDate(input);
console.log(cdate, cdate.getFullYear());
}
function getDate(input) {
var arr = [];
var seperator = ['/', '-'];
var year, month, date;
var yearIndex = 2;
var result = undefined;
seperator.forEach(function(s) {
if (input.indexOf(s) > -1)
arr = input.split(s);
});
if (arr.length > 1) {
// Set year
if (arr[0] > 1000) {
year = arr[0]
yearIndex = 0;
} else if (arr[2] > 1000) {
year = arr[2];
yearIndex = 2;
}
// set month and date
// If string starts with year, assume yyyy/mm/dd
if (yearIndex === 0) {
month = arr[1]
date = arr[2]
} else {
// If value greater than 12, assume it as date and other one as month
if (arr[0] > 12) {
date = arr[0]
month = arr[1]
} else if (arr[1] > 12) {
date = arr[1]
month = arr[0]
}
// If none of the value is ggreater than 12, assume default format of dd/mm/yyyy
else {
date = arr[0]
month = arr[1]
}
}
result = new Date(year, month - 1, date);
}
return result;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input id="dpDate" type="text" placeholder="dd/mm/yyyy" value="15/2/2016" />
<button onclick="getYear()">Get Year</button>
regex_yearfirst = /\d{4}\W/;
regex_yearlast = /\d{4}\n/;
if (regex_yearfirst.test(outputJSon["Date"])) {
yearIndex=0;
}
else if (regex_yearlast.test(outputJSon["Date"])) {
yearIndex=2;
}
else {
console.log("date format not recognized")
}
if (parseInt(outputJSon["Date"].split('/')[yearIndex]) === currentYear) {
outputDate = outputJSon["Date"];
}
else {
outputDate = outputJSon["Date"].replace(outputJSon["Date"].split('/')[yearIndex], currentYear)
}
Related
I am trying to compare months from a form, which are 1,2,3,4,5,6,7,8,9,10,11,12 to getMonth()
I have been trying to figure it out for a while, and tried parsing to Int and making sure the Int's
are the same, i.e. single digits, but to no effect.
function checkCard() {
var cardYearError = document.getElementById("cardYearError");
var monthError = document.getElementById("cardMonthError");
var date = new Date();
var month = parseInt(date.getMonth()+1);
var cardMonth = parseInt(document.getElementById("cardmonth"));
var year = parseInt(date.getFullYear());
var cardYear = parseInt(document.getElementById("cardyear"));
if (year > cardYear) {
cardYearError.innerHTML="Sorry your card has expired :1";
cardYear.focus();
cardYearError.style.color="red";
return false;
}
cardYearError.innerHTML="";
if ( year === cardYear && cardMonth < month) {
monthError.innerHTML="Sorry your card has expired :2";
cardMonth.focus();
monthError.style.color="red";
return false;
}
cardMonthError.innerHTML="";
return;
}
The year comparison works fine, but the second if statement will not work for some reason unknown to me.
you need to check year, cardYear, cardMonth & month first !
for this you have to log all these variables.
and you did not get the value of these two given lines
var cardMonth = parseInt(document.getElementById("cardmonth").value));
var cardYear = parseInt(document.getElementById("cardyear").value));
now you can try this code and let me if its work fine.
function checkCard() {
var cardYearError = document.getElementById("cardYearError");
var monthError = document.getElementById("cardMonthError");
var date = new Date();
var month = parseInt(date.getMonth()+1);
var cardMonth = parseInt(document.getElementById("cardmonth").value));
var year = parseInt(date.getFullYear());
var cardYear = parseInt(document.getElementById("cardyear").value));
if (year > cardYear) {
cardYearError.innerHTML="Sorry your card has expired :1";
cardYear.focus();
cardYearError.style.color="red";
return false;
}
cardYearError.innerHTML="";
console.log(`${year} === ${cardYear} && ${cardMonth} < ${month}`)
if ( year === cardYear && cardMonth < month) {
monthError.innerHTML="Sorry your card has expired :2";
cardMonth.focus();
monthError.style.color="red";
return false;
}
cardMonthError.innerHTML="";
return;
}
I fixed it by changing the html value properties. It was reading the value and not what was between the tags as I had thought.
I tried using this:
var demo = document.getElementById("demo");
demo.innerHTML=month+" "+cardMonth+" "+year+" "+cardYear;
To print the values and troubleshooted as I don't have breakpoints in notepad++.
Thanks for giving me the idea.
Date can be in any format 25.10.2018 or 25.10.18 or 25-12-2018 or 25-12-18, need to change this date to 25/10/2018 this format only.
The user can input date in any above format, I need to distinguish first in which format then needs to change its format to the desired format.
I do not want to use any 3rd Party JavaScript file.
You can easily do this using momentjs.
Check below working examples:
let d1 = "25.10.2018";
console.log(moment(d1, "DD.MM.YYYY").format("DD/MM/YYYY"));
let d2 = "25.10.18";
console.log(moment(d2, "DD.MM.YY").format("DD/MM/YYYY"));
let d3 = "25-12-2018";
console.log(moment(d3, "DD-MM-YYYY").format("DD/MM/YYYY"));
let d4 = "25-12-18";
console.log(moment(d4, "DD-MM-YY").format("DD/MM/YYYY"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>
So your original date have included special character like .,- .So you can split with that characters and I add 0 for your month and date 1 digit.For year format , use new Date to get correct year even two digit have provided ....
var d = '12-4-88'; // '25.10.2018'; or 25.10.18 or 25-12-2018
d = d.split(/[.\-_]/);
d.forEach((v,k) => {
if(v < 10) d[k] = 0 + v;
if(k == 2 && v.length == 2) {
var year = new Date(v+"-01-01");
d[k] = year.getFullYear();
}
})
console.log(d[0] + '/' + d[1] + '/' + d[2]);
You will need Date to preserve full year as two digits year value evaluates invalid date.
function parse(str) {
var result = {
'input': str,
'output': null
};
var tmp = str.split(/[\.|\-]/);
if (tmp && 3 === tmp.length) {
if (2 === tmp[2].length) {
tmp[2] = new Date().getFullYear().toString().substr(0, 2) + tmp[2];
}
if (1 === tmp[1].length) {
tmp[1] = '0' + tmp[1];
}
result.output = tmp.join('/');
}
return result;
}
console.log(parse("25.10.2018"));
console.log(parse("25.10.18"));
console.log(parse("25-10-2018"));
console.log(parse("25-10-18"));
console.log(parse("25.1.2018"));
console.log(parse("05.10.2018"));
function replaceAll(string, search, replacement) {
return string.replace(new RegExp(search, 'g'), replacement);
};
const newDate = replaceAll(oldDate, '.', '/');
String.prototype.replaceAll = function(str1, str2, ignore)
{
return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
}
"25.10.2018".replaceAll(".", "/");
I have a myDate variable with the value 18-Nov-2013.Each day its value is being changed.Tommorow this myDate variable will have the value 19-Nov-2013.I have a list of values that i have mapped into a single array named exclude which contains some dates that are to be excluded ,now it has values ["20-Nov-2013",21-Nov-2013", "23-Nov-2010"] .How could i filter my value from the list of values from the exclude array.I need the next highest value from the array.So here i need the value 22-Nov-2013 after tommorrows date.Could someone help me with this.
var excluded = ["30-Nov-2013","01-Dec-2013","02-Dec-2013"];
var myDate = "29-Nov-2013";
var month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var current = new Date(myDate);
while(true){
current = new Date((current.getDate()+1<10? "0"+(current.getDate()+1):(current.getDate()+1))+ "-" + month[current.getMonth()] + "-" + current.getFullYear());
var checkDate = (current.getDate()<10? "0"+(current.getDate()):(current.getDate()))+ "-" + month[current.getMonth()] + "-" + current.getFullYear();//this is necessary for when the +1 on day of month passes the month barrier
if(-1 == excluded.indexOf(checkDate))
break;
}
alert(checkDate);
I don't know if this is the best approach, or if is the best algorithm, but you may try this:
var myDate = ["17-Nov-2013", "18-Nov-2013"];
var excluded = ["20-Nov-2013", "21-Nov-2013", "23-Nov-2013"];
var months = {"Nov": 10}; // Add others months "Jan": 1, "Fev": 2 etc...
function findExcluded(date)
{
for (var i = 0; i < excluded.length; i++)
{
if (excluded[i] === date)
{
return true;
}
}
return false;
}
function nextDate()
{
var last = myDate[(myDate.length - 1)];
var s = last.split("-");
var d = new Date(s[2], months[s[1]], s[0]);
var next = new Date(d);
var chkDate = "";
do
{
next.setDate(next.getDate() + 1);
chkDate = next.getDate() + "-" + findMonth(next.getMonth()) + "-" + next.getFullYear();
} while(findExcluded(chkDate));
return chkDate;
}
function findMonth(m)
{
var i = 10; // When you fill all months on 'months' array, this variable should start at '0' in order to loop to works.
for (var month in months)
{
if (i == m)
{
return month;
}
i++;
}
}
var nd = nextDate();
alert(nd);
See it woring here.
No code ? Well here will be my method:
1.Get next date for mydate. Say that is var nextDate.
2.Check whether that date exist in the array.
3.If exists add one more day to nextDate. Again check in the array.
4.Do it until you get a date which is not present in your exclude array
For checking whether it exists in the array you can use arrValues.indexOf(nextDateInProperFormat) > -1
I have an array of unavailable dates set at unavailableDates and weekends.
Array:
<script type="text/javascript">//<![CDATA[
var unavailableDates = [];
{foreach $fixed.rows as $row}
var row = {};
row['date_from'] = "{$row.fixed_date_from.value}";
row['date_until'] = "{$row.fixed_date_until.value}";
row['name'] = "{$row.fixed_name.value} ({$row.fixed_type.value})";
unavailableDates.push(row);
{/foreach}
//]]></script>
Q1) How can I add an extra check for the until date. I have got it working as shown below for the from date?
Q2) Can I improve the code to use in_array instead of loop through each of the dates for each calendar day?
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
var unavailableDays = ["Saturday","Sunday"];
$("#.datePicker").datepicker($.extend(true, {}, $.initDatePickers.defaults, {
beforeShowDay: function(date) {
ymd = date.getFullYear() + "-" + ("0"+(date.getMonth()+1)).slice(-2) + "-" + ("0"+date.getDate()).slice(-2);
day = new Date(ymd).getDay();
result = null;
// Check if date in unavailable array or weekend
for(var i = 0; i < unavailableDates.length; i++){
if ((ymd == unavailableDates[i].date_from) && $.inArray(days[day], unavailableDays) < 0) {
return [false,"unavailable",unavailableDates[i].name];
}
}
if(result){
return result;
} else {
return [true, "available", ""];
}
}
}));
Use the befreShowDay option to parse your data array to determine if day is selectable or not
beforeShowDayType: Function( Date date )
A function takes a date as a parameter and must return an array with [0] equal to true/false indicating whether or not this date is selectable, 1 equal to a CSS class name or "" for the default presentation, and [2] an optional popup tooltip for this date. It is called for each day in the datepicker before it is displayed.
Can anyone help me in finding the solution
i just want to compare two dates in dd/mm/yyyy format.
function compareDate(dt1 , dt2 , formatString){var returnVal = 2;
var dt1Parts;
var dt2Parts;
var dt1dd;
var dt1mm;
var dt1yyyy;
var dt2dd;
var dt2mm;
var dt2yyyy;
if(formatString == 'dd/mm/yyyy'){
dt1Parts = dt1.split('/');
dt2Parts = dt2.split('/');
dt1dd = parseInt(dt1Parts[0]);
dt1mm = parseInt(dt1Parts[1]);
dt1yyyy = parseInt(dt1Parts[2]);
dt2dd = parseInt(dt2Parts[0]);
dt2mm = parseInt(dt2Parts[1]);
dt2yyyy = parseInt(dt2Parts[2]);
}
else if(formatString == 'dd-mm-yyyy'){
dt1Parts = dt1.split('-');
dt2Parts = dt2.split('-');
dt1dd = parseInt(dt1Parts[0]);
dt1mm = parseInt(dt1Parts[1]);
dt1yyyy = parseInt(dt1Parts[2]);
dt2dd = parseInt(dt2Parts[0]);
dt2mm = parseInt(dt2Parts[1]);
dt2yyyy = parseInt(dt2Parts[2]);
}else{
alert(formatString+' format is not supported.');
}
if(dt1yyyy == dt2yyyy && dt1mm == dt2mm && dt1dd == dt2dd){
returnVal = 0;
}
else if(dt1yyyy > dt2yyyy){
returnVal = 1 ;
}else if(dt1yyyy == dt2yyyy ){
if(dt1mm > dt2mm){
returnVal = 1;
}else if(dt1mm == dt2mm){
if(dt1dd > dt2dd){
returnVal = 1;
}else{
returnVal = -1;
}
}else{
returnVal = -1;
}
}else{
returnVal = -1;
}
return returnVal;
}
Thanks in advance,
Shilpa
Invert the strings to yyyy/mm/dd, or convert them to a number or Date object.
The simplest way just for comparison would be ASCII order. Invert using something like this:
function invert(date) {
return date.split(/[/-]/).reverse().join("")
}
function compareDates(date1, date2) {
return invert(date1).localeCompare(invert(date2));
}
Here's how you convert that string format to a date:
var myString = "17/07/1979",
correctFormat = myString.replace(/(\d+)\/(\d+)\/(\d+)/, "$3/$2/$1"),
myDate = new Date(correctFormat);
Without knowing what language or class libs you're working with:
Method 1: Resort your strings to be yyyymmdd and the do string compare.
Method 2: Stuff yyyy mm and dd into the high, middle, and low bits of an integer and compare.
The easiest way is probably to create 2 javascript Date objects from your input string. You could achieve that by chopping your input into day, month and year. You can use the 'substring' function for that.
Then you can do:
var firstDate = new Date(year1, month1, day1);
var secondDate = new Date(year2, month2, day2);
Once you have 2 date objects, you can use the normal compare operators:
if (firstDate > secondDate)
// do something
else
...
Try this
var date1=new Date('your date1 string');
var date2=new Date('your date2 string');
var difference=new Date(date1.getTime()-date2.getTime());
if ($.datepicker.parseDate('dd/mm/yy', fDate) > $.datepicker.parseDate('dd/mm/yy', tDate)) {
//do something
}
You can compare two dates.Here I compare from date greater than to date
try this