Get days left till end of the month with moment.js - javascript

I want to display or hide a link depending on whether there are less than 2 weeks left in the month, using moment.js, but I'm not sure the correct way to go about it.
Currently I have...
if (moment().endOf('month')<=(13, 'days'))
{
//do link stuff here
}
...but I don't think that's the correct way of doing it. It certainly isn't doing anything anyway. Could anyone give me any pointers? Thanks in advance.

You could do something like this:
var a = moment().endOf('month');
var b = moment();
if(a.diff(b, 'days') <= 13)
{
//do something
}

If you're looking for a plain javascript version, I've wrote this function:
function getMonthDaysLeft(){
date = new Date();
return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate() - date.getDate();
}

Maybe something like this can help.
const d = moment();
const currentDay = d.get("date");
const daysInMonth = d.daysInMonth();
const remainingDays = daysInMonth - currentDay;
console.log(remainingDays <= 13)

Related

Minimum start date of datepicker

Sorry to do this guys, I have zero experience with Java or wix code, you would expect something as basic as what I am after would have a default in built setting for.
I have a date picker on a form, I want the minimum to be now()+3 - but have no idea where to start.
I did read a post that offered the below code:
$w.onReady(function () {
let today = new Date();
let startDate = new Date(today);
startDate.setDate(startDate.getDate() + 3);
let endDate = new Date(today);
endDate.setMonth(endDate.getMonth() + 1); // End Date +1 month from today //
// Set min & max dates //
$w("#datePicker1").minDate = startDate;
$w("#datePicker1").maxDate = endDate;
});
});
However I appear to get this error message:
public/pages/qepnx.js/qepnx.js: Unexpected token (15:0)
Any help would be greatly appreciated.
Thanks!
Okay after much pain I've figured it out, it turns out JS is a lot less forgiving than languages like VBA, { or ( incorrectly placed parenthesis will throw the whole code out which I learnt the hard way.
Code as below:
$w.onReady( function() {
var badDate1 = new Date();
badDate1.setDate(badDate1.getDate());
var badDate2 = new Date();
badDate2.setDate(badDate2.getDate() + 1);
var badDate3 = new Date();
badDate3.setDate(badDate3.getDate() + 2);
$w("#datePicker1").disabledDates = [badDate1, badDate2, badDate3];
})
I'm sure someone who actually knows JS will be appalled by this, but it's simple code and does the job
Thanks

Check If date is over a 2 weeks old

I’m trying to create a if statement that checks a date against the current date and throw a error if its less that 2 weeks old.
My current code
const moment = require('moment')
const today = moment().format()
const createdDate = '2020-07-30'
if (createdDate <= today ) {
console.log('Good')
} else {
console.log('Bad')
};
console.log(today)
Would appreciate any suggestions.
You can use moments subtract feature along with isSameOrAfter.
There is another option where you add two weeks to the createdDate and compare that today as well. Whichever makes more sense for you.
const today = moment();
const createdDate = moment("2020-08-30")
if (today.subtract(2, 'weeks').isSameOrAfter(createdDate)) {
console.log('good')
} else {
console.log('bad')
}
You can do this two ways and you can choose what suit you better. Both solution below will perfectly for your scenario.
You can simply use moment diff function by getting the difference of days in numbers and if the difference is more then or equal to 14 days then its good else it will be bad.
Using diff function
Live Demo:
var today = moment().startOf('day')
var createdDate = moment("2020-07-30", "YYYY-MM-DD").startOf('day')
var diff = today.diff(createdDate, 'days')
if (diff >= 14) {
console.log('Good')
} else {
console.log('Bad')
};
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.js"></script>
Using add function and clone function get the results
You can use add function along with clone and using startOf day function to make sure we always get the date from day start not when when performed the operation to check for comparison.
Live Demo:
let today = moment().startOf('day').format('YYYY-MM-DD') //today
let createdDate = moment('2020-07-30', 'YYYY-MM-DD').clone().add(14, 'days').startOf('day').format('YYYY-MM-DD') //created date minus two weeks
if (createdDate <= today) {
console.log('Good')
} else {
console.log('Bad')
};
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.js"></script>
You can use add feature of Moment as well.
const today = moment();
const createdDate = moment("2020-07-30")
if (createdDate.add(2, 'weeks').isSameOrAfter(today)) {
console.log('good to go!')
} else {
console.log('bad')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js" integrity="sha256-ZsWP0vT+akWmvEMkNYgZrPHKU9Ke8nYBPC3dqONp1mY=" crossorigin="anonymous"></script>

Convert SQL datetime to string or Date object [duplicate]

How can I convert a string to a date time object in javascript by specifying a format string?
I am looking for something like:
var dateTime = convertToDateTime("23.11.2009 12:34:56", "dd.MM.yyyy HH:mm:ss");
Use new Date(dateString) if your string is compatible with Date.parse(). If your format is incompatible (I think it is), you have to parse the string yourself (should be easy with regular expressions) and create a new Date object with explicit values for year, month, date, hour, minute and second.
I think this can help you: http://www.mattkruse.com/javascript/date/
There's a getDateFromFormat() function that you can tweak a little to solve your problem.
Update: there's an updated version of the samples available at javascripttoolbox.com
#Christoph Mentions using a regex to tackle the problem. Here's what I'm using:
var dateString = "2010-08-09 01:02:03";
var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
var dateArray = reggie.exec(dateString);
var dateObject = new Date(
(+dateArray[1]),
(+dateArray[2])-1, // Careful, month starts at 0!
(+dateArray[3]),
(+dateArray[4]),
(+dateArray[5]),
(+dateArray[6])
);
It's by no means intelligent, just configure the regex and new Date(blah) to suit your needs.
Edit: Maybe a bit more understandable in ES6 using destructuring:
let dateString = "2010-08-09 01:02:03"
, reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/
, [, year, month, day, hours, minutes, seconds] = reggie.exec(dateString)
, dateObject = new Date(year, month-1, day, hours, minutes, seconds);
But in all honesty these days I reach for something like Moment
No sophisticated date/time formatting routines exist in JavaScript.
You will have to use an external library for formatted date output, "JavaScript Date Format" from Flagrant Badassery looks very promising.
For the input conversion, several suggestions have been made already. :)
Check out Moment.js. It is a modern and powerful library that makes up for JavaScript's woeful Date functions (or lack thereof).
Just for an updated answer here, there's a good js lib at http://www.datejs.com/
Datejs is an open source JavaScript Date library for parsing, formatting and processing.
var temp1 = "";
var temp2 = "";
var str1 = fd;
var str2 = td;
var dt1 = str1.substring(0,2);
var dt2 = str2.substring(0,2);
var mon1 = str1.substring(3,5);
var mon2 = str2.substring(3,5);
var yr1 = str1.substring(6,10);
var yr2 = str2.substring(6,10);
temp1 = mon1 + "/" + dt1 + "/" + yr1;
temp2 = mon2 + "/" + dt2 + "/" + yr2;
var cfd = Date.parse(temp1);
var ctd = Date.parse(temp2);
var date1 = new Date(cfd);
var date2 = new Date(ctd);
if(date1 > date2) {
alert("FROM DATE SHOULD BE MORE THAN TO DATE");
}
time = "2017-01-18T17:02:09.000+05:30"
t = new Date(time)
hr = ("0" + t.getHours()).slice(-2);
min = ("0" + t.getMinutes()).slice(-2);
sec = ("0" + t.getSeconds()).slice(-2);
t.getFullYear()+"-"+t.getMonth()+1+"-"+t.getDate()+" "+hr+":"+min+":"+sec
External library is an overkill for parsing one or two dates, so I made my own function using Oli's and Christoph's solutions. Here in central Europe we rarely use aything but the OP's format, so this should be enough for simple apps used here.
function ParseDate(dateString) {
//dd.mm.yyyy, or dd.mm.yy
var dateArr = dateString.split(".");
if (dateArr.length == 1) {
return null; //wrong format
}
//parse time after the year - separated by space
var spacePos = dateArr[2].indexOf(" ");
if(spacePos > 1) {
var timeString = dateArr[2].substr(spacePos + 1);
var timeArr = timeString.split(":");
dateArr[2] = dateArr[2].substr(0, spacePos);
if (timeArr.length == 2) {
//minutes only
return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]));
} else {
//including seconds
return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]), parseInt(timeArr[2]))
}
} else {
//gotcha at months - January is at 0, not 1 as one would expect
return new Date(parseInt(dateArr[2]), parseInt(dateArr[1] - 1), parseInt(dateArr[0]));
}
}
Date.parse() is fairly intelligent but I can't guarantee that format will parse correctly.
If it doesn't, you'd have to find something to bridge the two. Your example is pretty simple (being purely numbers) so a touch of REGEX (or even string.split() -- might be faster) paired with some parseInt() will allow you to quickly make a date.
Just to give my 5 cents.
My date format is dd.mm.yyyy (UK format) and none of the above examples were working for me. All the parsers were considering mm as day and dd as month.
I've found this library: http://joey.mazzarelli.com/2008/11/25/easy-date-parsing-with-javascript/
and it worked, because you can say the order of the fields like this:
>>console.log(new Date(Date.fromString('09.05.2012', {order: 'DMY'})));
Wed May 09 2012 00:00:00 GMT+0300 (EEST)
I hope that helps someone.
Moment.js will handle this:
var momentDate = moment('23.11.2009 12:34:56', 'DD.MM.YYYY HH:mm:ss');
var date = momentDate.;
You can use the moment.js library for this. I am using only to get time-specific output but you can select what kind of format you want to select.
Reference:
1. moment library: https://momentjs.com/
2. time and date specific functions: https://timestamp.online/article/how-to-convert-timestamp-to-datetime-in-javascript
convertDate(date) {
var momentDate = moment(date).format('hh : mm A');
return momentDate;
}
and you can call this method like:
this.convertDate('2020-05-01T10:31:18.837Z');
I hope it helps. Enjoy coding.
To fully satisfy the Date.parse convert string to format dd-mm-YYYY as specified in RFC822,
if you use yyyy-mm-dd parse may do a mistakes.
//Here pdate is the string date time
var date1=GetDate(pdate);
function GetDate(a){
var dateString = a.substr(6);
var currentTime = new Date(parseInt(dateString ));
var month =("0"+ (currentTime.getMonth() + 1)).slice(-2);
var day =("0"+ currentTime.getDate()).slice(-2);
var year = currentTime.getFullYear();
var date = day + "/" + month + "/" + year;
return date;
}

checking day difference with moment.js

I want to use moment.js to check if a date is today. Does anyone know how to do that?
I tried moment(yesterday_date).diff(moment(), 'days'). This outputs a 1 only if there is a 24 hour difference.
Any ideas? Any help would be appreciated.
You can use startOf('day') and isSame() to do this...
var someDate = moment("2014-07-17 05:00:00");
var isToday = someDate.startOf('day').isSame(moment().startOf('day'));
Fiddle
You could do something like
moment().unix() - moment(yesterday_date).unix();
That should give you the difference in milliseconds. Then you just need to convert to whichever time unit you need.
Edit:
Just realised you want to check whether it's today. Then something like this should work:
function isToday(dateString) {
var today = moment();
var prevDate = moment(dateString);
return today.date() == prevDate.date() && today.month() == prevDate.month() && today.year() == prevDate.year();
}

How can I convert string to datetime with format specification in JavaScript?

How can I convert a string to a date time object in javascript by specifying a format string?
I am looking for something like:
var dateTime = convertToDateTime("23.11.2009 12:34:56", "dd.MM.yyyy HH:mm:ss");
Use new Date(dateString) if your string is compatible with Date.parse(). If your format is incompatible (I think it is), you have to parse the string yourself (should be easy with regular expressions) and create a new Date object with explicit values for year, month, date, hour, minute and second.
I think this can help you: http://www.mattkruse.com/javascript/date/
There's a getDateFromFormat() function that you can tweak a little to solve your problem.
Update: there's an updated version of the samples available at javascripttoolbox.com
#Christoph Mentions using a regex to tackle the problem. Here's what I'm using:
var dateString = "2010-08-09 01:02:03";
var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
var dateArray = reggie.exec(dateString);
var dateObject = new Date(
(+dateArray[1]),
(+dateArray[2])-1, // Careful, month starts at 0!
(+dateArray[3]),
(+dateArray[4]),
(+dateArray[5]),
(+dateArray[6])
);
It's by no means intelligent, just configure the regex and new Date(blah) to suit your needs.
Edit: Maybe a bit more understandable in ES6 using destructuring:
let dateString = "2010-08-09 01:02:03"
, reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/
, [, year, month, day, hours, minutes, seconds] = reggie.exec(dateString)
, dateObject = new Date(year, month-1, day, hours, minutes, seconds);
But in all honesty these days I reach for something like Moment
No sophisticated date/time formatting routines exist in JavaScript.
You will have to use an external library for formatted date output, "JavaScript Date Format" from Flagrant Badassery looks very promising.
For the input conversion, several suggestions have been made already. :)
Check out Moment.js. It is a modern and powerful library that makes up for JavaScript's woeful Date functions (or lack thereof).
Just for an updated answer here, there's a good js lib at http://www.datejs.com/
Datejs is an open source JavaScript Date library for parsing, formatting and processing.
var temp1 = "";
var temp2 = "";
var str1 = fd;
var str2 = td;
var dt1 = str1.substring(0,2);
var dt2 = str2.substring(0,2);
var mon1 = str1.substring(3,5);
var mon2 = str2.substring(3,5);
var yr1 = str1.substring(6,10);
var yr2 = str2.substring(6,10);
temp1 = mon1 + "/" + dt1 + "/" + yr1;
temp2 = mon2 + "/" + dt2 + "/" + yr2;
var cfd = Date.parse(temp1);
var ctd = Date.parse(temp2);
var date1 = new Date(cfd);
var date2 = new Date(ctd);
if(date1 > date2) {
alert("FROM DATE SHOULD BE MORE THAN TO DATE");
}
time = "2017-01-18T17:02:09.000+05:30"
t = new Date(time)
hr = ("0" + t.getHours()).slice(-2);
min = ("0" + t.getMinutes()).slice(-2);
sec = ("0" + t.getSeconds()).slice(-2);
t.getFullYear()+"-"+t.getMonth()+1+"-"+t.getDate()+" "+hr+":"+min+":"+sec
External library is an overkill for parsing one or two dates, so I made my own function using Oli's and Christoph's solutions. Here in central Europe we rarely use aything but the OP's format, so this should be enough for simple apps used here.
function ParseDate(dateString) {
//dd.mm.yyyy, or dd.mm.yy
var dateArr = dateString.split(".");
if (dateArr.length == 1) {
return null; //wrong format
}
//parse time after the year - separated by space
var spacePos = dateArr[2].indexOf(" ");
if(spacePos > 1) {
var timeString = dateArr[2].substr(spacePos + 1);
var timeArr = timeString.split(":");
dateArr[2] = dateArr[2].substr(0, spacePos);
if (timeArr.length == 2) {
//minutes only
return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]));
} else {
//including seconds
return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]), parseInt(timeArr[2]))
}
} else {
//gotcha at months - January is at 0, not 1 as one would expect
return new Date(parseInt(dateArr[2]), parseInt(dateArr[1] - 1), parseInt(dateArr[0]));
}
}
Date.parse() is fairly intelligent but I can't guarantee that format will parse correctly.
If it doesn't, you'd have to find something to bridge the two. Your example is pretty simple (being purely numbers) so a touch of REGEX (or even string.split() -- might be faster) paired with some parseInt() will allow you to quickly make a date.
Just to give my 5 cents.
My date format is dd.mm.yyyy (UK format) and none of the above examples were working for me. All the parsers were considering mm as day and dd as month.
I've found this library: http://joey.mazzarelli.com/2008/11/25/easy-date-parsing-with-javascript/
and it worked, because you can say the order of the fields like this:
>>console.log(new Date(Date.fromString('09.05.2012', {order: 'DMY'})));
Wed May 09 2012 00:00:00 GMT+0300 (EEST)
I hope that helps someone.
Moment.js will handle this:
var momentDate = moment('23.11.2009 12:34:56', 'DD.MM.YYYY HH:mm:ss');
var date = momentDate.;
You can use the moment.js library for this. I am using only to get time-specific output but you can select what kind of format you want to select.
Reference:
1. moment library: https://momentjs.com/
2. time and date specific functions: https://timestamp.online/article/how-to-convert-timestamp-to-datetime-in-javascript
convertDate(date) {
var momentDate = moment(date).format('hh : mm A');
return momentDate;
}
and you can call this method like:
this.convertDate('2020-05-01T10:31:18.837Z');
I hope it helps. Enjoy coding.
To fully satisfy the Date.parse convert string to format dd-mm-YYYY as specified in RFC822,
if you use yyyy-mm-dd parse may do a mistakes.
//Here pdate is the string date time
var date1=GetDate(pdate);
function GetDate(a){
var dateString = a.substr(6);
var currentTime = new Date(parseInt(dateString ));
var month =("0"+ (currentTime.getMonth() + 1)).slice(-2);
var day =("0"+ currentTime.getDate()).slice(-2);
var year = currentTime.getFullYear();
var date = day + "/" + month + "/" + year;
return date;
}

Categories

Resources