I have a table to which i dynamically add rows. The number of days is equal to the date difference of the dates inserted by user. On the dynamic rows i want to add three fields. The first two are date and day filed. For that I need to know the next date and the corresponding day. For example user enters 10-2-2012. I need to insert The next dates like 17-2-2012,18-2-2012... and corresponding days like Wednesday, Thursday..etc
I have used the following function to get next date
function getTomorrow(d,offset)
{
if (!offset)
{
offset = 1
}
return new Date(new Date().setDate(d.getDate() + offset));
}
But it shows error 16-2-2012 has no getDate() function. Am not able to find next date and the corresponding day. Is there any way to get it?
You have to convert the string d into a Date object:
function getTomorrow(d,offset){
if (!offset){
offset = 1;
}
if(typeof(d) === "string"){
var t = d.split("-"); /* splits dd-mm-year */
d = new Date(t[2],t[1] - 1, t[0]);
// d = new Date(t[2],t[1] - 1, t[0] + 2000); /* for dd-mm-yy */
}
return new Date(d.setDate(d.getDate() + offset));
}
document.write(getTomorrow('16-02-2012',20) + ' test');
var k = getTomorrow('16-02-2012',1);
var myTime = k.getDate()+'-'+(k.getMonth()+1)+'-'+k.getFullYear();
alert(myTime);
JSFiddle Demo. See also http://www.w3schools.com/jsref/jsref_obj_date.asp.
var d=new Date();
d.setTime((d.getTime() + 86400 * 1000*1));
document.write(d);
document.write(d.getDay()+"-"+parseInt(d.getMonth()+1)+"-"+d.getFullYear());
if you need to know the date of day after tommorow , just change 1000*1 to 1000*2.
i giving a example
var year = 2010, month = 9, day = 14;
// The value of `meses`
var offset = 1; // Tomorow
var future_date = new Date(year, month , day+offset);
console.log(future_date);
Related
I wrote a simple javascript function which converts string to date (in format 'dd.MM.yyyy HH.mm').
For extracting parts of that string, I've used slice method.
What is strange to me is that only day is returned as expected. All other variables are simply empty strings.
What am I doing wrong?
(
function(){
alert(GetDateFromStringDateTime("20.04.2017 18:15"));
}
)();
function GetDateFromStringDateTime(dateStr){
var day = dateStr.slice(0,2);
var month = dateStr.slice(3,2);
var year = dateStr.slice(6,4);
var hour = dateStr.slice(11,2);
var minute = dateStr.slice(14,2);
return new Date(year,month,day,hour,minute);
}
Picture from console window (month, year, hour and minute are empty strings):
String#slice() use a start and end parameter which are both zero-based index
console.log(GetDateFromStringDateTime("20.04.2017 18:15"));
function GetDateFromStringDateTime(dateStr) {
var day = dateStr.slice(0, 2);
var month = dateStr.slice(3, 5);
var year = dateStr.slice(6, 10);
var hour = dateStr.slice(11, 13);
var minute = dateStr.slice(14, 16);
console.log(day);
console.log(month);
console.log(year);
console.log(hour);
console.log(minute);
return new Date(year, month, day, hour, minute);
}
Use String.prototype.substr instead of slice
How can I check that a date is greater than or less than the specified date using javascript by passing the month and year only in MMM-YYYY Format.
For example :
Let the user selects JUL from month dropdown and 2016 from years dropdown ,
Now How can I check that the selected values are greater than / less than JUN 2016 .
I've taken the input in Session variables as session("month") , session("yrs").
I've tried the following but nothing happens :
var d1 = new Date('JUN-2016')
var d2 = new Date(<% =session("month")+"-"+session("yrs") %>) )
if(d2.getTime() > d2.getTime())
{
alert('Greater than jun 2016');
}
else
{
alert('Less than jun 2016');
}
I've gone through this link Compare two dates with JavaScript but didn't find the solution for my condition.
As this application is developed on VB so i don't have much knowledge about that.
How can I resolve this .
Please suggest
Thanks in advance.
Try this -
var x = new Date('JUN-2016');
var y = new Date('MAY-2016');
console.log(+x < +y);
console.log(+x > +y);
console.log(+x === +y);
First convert it to date object
// convert to a parseable date string:
var dateStrA = "28/12/2013 16:20:22".replace( /(\d{2})\/(\d{2})\/(\d{4})/, "$2/$1/$3");
var dateStrB = "28/12/2013 16:20:11".replace( /(\d{2})\/(\d{2})\/(\d{4})/, "$2/$1/$3");
// now you can compare them using:
new Date(dateStrA) > new Date(dateStrB);
var date1 = Math.ceil(Math.abs(first date) / (1000 * 3600 * 24));
var date2 = Math.ceil(Math.abs(second date) / (1000 * 3600 * 24));
if(date1 > date2 )
alert("date1");
else
alert("date2");
You just have to do a simple compare of dates. Please read more about "Date" here: http://www.w3schools.com/js/js_date_methods.asp
Maybe this code might help:
var day = 1; // Since you don't care about the day just use the first day
var month = session("month"); // Use the number of the month instead of the name
var year = session("yrs");
var dateJune = Date.parse("2016-07-01"); // June
var dateInput = Date.parse(year + "-" + month + "-" + day);
// Compare dates
if (dateJune > dateInput) {
// The input is before june
} else if (dateJune < dateInput) {
// The input is after june
} else {
// It is june
}
You need a valid date format to be able to parse the date. Instead of getting "JUN" from your select box it would be better to get the number of the month instead. A select box should look like this:
<select>
<option value="01">Jan</option>
<option value="02">Feb</option>
...
</select>
If this is not an option you can use a function that calculates the number for you if you know then string values that your month variable might have:
function (nameOfMonth) {
switch (nameOfMonth) {
case 'Jan':
return "01";
case 'Feb':
return "02";
....
}
}
I'm attempting to return different days based on a given date, such as the first Monday of the week, the Friday of the week, as well as days in previous and following weeks so that I can figure out the start and end of my pay periods (for my two jobs, each are different) as well as the pay date for that period.
When I remove the Logger.log("Prev Monday > " + addDays(pMonday, -7));
the next line's value changes. What is removed line doing to mess up the following one?
I'm using this in Google App Scripts so I can pull data from a Google Calendar to a Google Sheet easily. It also means no extra libraries.
function test_monday(){
var theDate = new Date();
theDate.setDate(16);
theDate.setMonth(5);
theDate.setFullYear(2016);
theDate.setHours(12,0,0,0)
Logger.log(theDate);
var pMonday = new Date();
pMonday = getMonday( theDate ) ;
Logger.log("pMonday: " + pMonday)
Logger.log("Prev Monday > " + addDays(pMonday, -7));
Logger.log("Following Friday > " + addDays(pMonday, 4));
}
function getMonday( date ) {
var day = date.getDay() || 7;
if( day !== 1 )
date.setHours(-24 * (day - 1));
return date;
}
function addDays(d, n){
var date = new Date();
date = d;
var offset = n;
date.setHours(24 * ( offset ));
return date;
}
date = d;
This line right here completely undoes the work you did in the previous line. It says that date is the exact same instance as d. That means that whenever you modify date (date.setHours(24 * offset)) you're also modifying d. You might as well be writing d.setHours(24 * offset) because they mean the same thing.
If you want to create a new Date object equal to another one, just pass the original into the Date constructor. So you could rewrite your function as:
function addDays(d, n) {
var date = new Date(d);
date.setHours(24 * n);
return date;
}
I am having an input date field in my form. In my date field
i need to alert an error if the input date is greater than any date i define before
here is what i code :
$(document).ready(function () {
var date = new Date(2016,2,1); //the defined date is 1 March 2016
var day = date.getDate();
var month = date.getMonth();
month = month + 1;
if(day < 10){
day = '0' + day;
}
if(month < 10){
month='0'+month;
}
someday = day + '/' + month + '/' + date.getFullYear();
$("#q1 input").blur(function(){ //#q1 is the ID for the input field.
if($('#q1 input').val() > someday){
alert('the input is bigger than the defined');
}else{
alert('the defined is bigger than the input ');
}
});
});
To compare Dates is very straight forward. Most operators coerce the operands to number, and Dates return their time value so to see if today is before or after say 1 March 2016, create two Dates and compare them:
var epoch = new Date(2016,2,1); // Create date for 2016-03-01T00:00:00
var now = new Date(); // Create a date for the current instant
now.setHours(0,0,0,0); // Set time to 00:00:00.000
if (now < epoch) {
alert('Before 1 March, 2016');
} else {
alert('On or after 1 March, 2016');
}
Or a bit more compact:
alert((now < epoch? 'Before':'On or after') + ' 1 March, 2016');
You might want to compare the values as in the date form, not the way you did.
Convert the input value into the form of date and compare it with the variable 'date'.
Compare the input date with the desired date that you defined. For example:
var d1 = new Date();
var d2 = new Date(d1);
var same = d1.getTime() === d2.getTime();
var notSame = d1.getTime() !== d2.getTime();
If you find it tricky, then there is an awesome js library called moment.js. It is very useful when playing with dates.
$(document).ready(function () {
var date=new Date(2016,2,1); //the defined date is 1 March 2016
var fixedDate = returnDate(date);// convert date in dd/mm/yyyy format
//#q1 input will search a child input inside an #q1 dom element, which probably not the case
// input#q1 will refer to input with id #q1
// You can directly query the input since it has id #q1 so #q1 input is not correct
$("#q1").blur(function(){ //#q1 is the ID for the input field.
var d2 = new Date($('#q1').val());
var inputDate = returnDate(d2); // convert input date in dd/mm/yyyy format
if(inputDate > fixedDate){ // compare two dates
console.log('the input is bigger than the defined');
}else{
console.log('the defined is bigger than the input ');
}
});
});
// Write a general function to convert date in dd/mm/yyyy format
function returnDate(date){
var day=date.getDate();
var month=date.getMonth();
month=month+1;
if(day<10){
day='0'+day;
}
if(month<10){
month='0'+month;
}
var someday=day+ '/' + month + '/' + date.getFullYear();
return someday;
}
JSFIDDLE
EDIT 1
Use ternary operator instead of if-else
inputDate > fixedDate? (console.log("the input is bigger than the defined")):(console.log("the defined is bigger than the input"))
with ternary operator
I have a string that contains 8 digits that represent a date. For example:
20120515
I'd like to compare it with today's date, created in this manner:
var currentDate = new Date();
How can I convert the "8 digit date string" to a suitable date format in order to compare it to currentDate?
Use the substring method and substring off 4 elements and assign it to your new date for the year. Then substring off two elements at a time and store the month and date accordingly.
var dateString = "20120515";
var year = dateString.substring(0,4);
var month = dateString.substring(4,6);
var day = dateString.substring(6,8);
var date = new Date(year, month-1, day);
var currentDate = new Date();
Now you can compare the two dates with the normal operators.
If you want a small date library you can use moment.js.
var a = moment("20120515", "YYYYMMDD");
// then use any of moment's manipulation or display functionality
a.format("MMM Do YYYY"); // May 15th 2012
a.fromNow(); // 14 hours ago
a.calendar(); // Today at 12:00 AM
To correctly handle the local time zone, it must explicitly summed to the calculated time
function dateStringToDate(dateString) {
try {
var year = dateString.substring(0, 4);
var month = dateString.substring(4, 6);
var day = dateString.substring(6, 8);
var date = new Date(year, month - 1, day);
const offset = date.getTimezoneOffset()
date = new Date(date.getTime() - (offset * 60 * 1000));
return date;
} catch (error) {
return null;
}
}
function dateStringToDate(dateString) {
try {
var year = dateString.substring(0, 4);
var month = dateString.substring(4, 6);
var day = dateString.substring(6, 8);
var date = new Date(year, month - 1, day);
const offset = date.getTimezoneOffset()
date = new Date(date.getTime() - (offset * 60 * 1000));
return date;
} catch (error) {
return null;
}
}
console.log(dateStringToDate("20211212"))
console.log(dateStringToDate("20211213"))
console.log(dateStringToDate("20211214"))
...some other "one-liner" ways to accomplish this:
(They take a value like dts='20020704'; and return date object [dt].)
var dt=new Date(dts.slice(0,4), (dts[4]+dts[5])-1, dts[6]+dts[7]);
...or...
var m=dts.match(/(....)(..)(..)/), dt=new Date(m[1],m[2]-1,m[3]);
...or...
var m=dts.match(/.{1,2}/g), dt=new Date(m[0]+m[1],m[2]-1,m[3]);
The last one's shortest, but the first is probably most efficient, since it doesn't use regex (but that's irrelevant, unless you're processing LOTS of data using this). I like the middle one best since it's easy to see what's happening.