I am trying to format a array of dates using moment.js but I get an error stating
dayOfWeek.format is not a function
I am correctly imported
var startOfWeek = moment().startOf('isoWeek');
var endOfWeek = moment().endOf('isoWeek');
var days = [];
var day = startOfWeek;
while (day <= endOfWeek) {
days.push(day.toDate());
day = day.clone().add(1, 'd');
}
var week = days.map(function(dayOfWeek, i){
console.log(dayOfWeek);
dayOfWeek.format("dddd, DD-MM-YYYY")
});
Your code will fail because dayOfWeek is not moment object.
To check if your variable is moment object use .isMoment:
moment.isMoment(dayOfWeek).
To fix your problem simply replace
dayOfWeek.format("dddd, DD-MM-YYYY")
with
moment(dayOfWeek).format("dddd, DD-MM-YYYY")
You are also missing return statement inside .map function.
Working example:
var startOfWeek = moment().startOf('isoWeek');
var endOfWeek = moment().endOf('isoWeek');
var days = [];
var day = startOfWeek;
while (day <= endOfWeek) {
days.push(day.toDate());
day = day.clone().add(1, 'd');
}
var week = days.map(function(dayOfWeek, i){
return moment(dayOfWeek).format("dddd, DD-MM-YYYY")
});
console.log(week);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
moment().format() function usage is not correct.
Current is:
dayOfWeek.format("dddd, DD-MM-YYYY")
Change to:
moment(dayOfWeek).format("dddd, DD-MM-YYYY")
Check here for more information: https://momentjs.com/docs/#/parsing/string-formats/
dayOfWeek = moment(dayOfWeek).format("dddd, DD-MM-YYYY");
Just a tip, You can also do this
var currentDate = moment(new Date()); // pass your date obj here.
console.log(currentDate.format('DD-MM-YY HH:mm:ss')); // later simply do this.
<script src="https://unpkg.com/moment#2.22.2/min/moment.min.js"></script>
Related
I am trying to create a date array between 2 dates.
[11/16/2018, 12/16/2018, 1/16/2019......11/16/2019]
I have the following code.
function dateRange(stDate, etDate) {
const dates = [];
var startDate = moment(new Date(stDate)).format("MM/DD/YYYY");
var endDate = moment(new Date(etDate)).format("MM/DD/YYYY");
var now = new Date(startDate);
while (startDate <= endDate) {
dates.push(new Date(now));
now = now.addMonths(1);
}
console.log("dateRange " + dates);
}
function RunLedgerAndPV() {
var stDate = "11/16/2018";
var etDate = "11/16/2019";
dateRange(stDate, etDate);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
Trying to debug it, it doesn't break or anything and it is returning the just the start and end date but doesn't push the date array. What am i doing wrong here?
Also, i have looked at the other posts regarding this and i have myself worked on date range in the past. However, i am clueless as to why this isn't working for me.
Any help is appreciated. Thank you!
There are quite a few inefficiencies and bugs in your code, too many to list really. A summary would include unnecessary creation and then re-stringifying of dates, unnecessary use of JS Date constructors and dodgy logic in your for loop.
Here's a version which will work correctly using just momentJS functionality:
function createLedger(stDate, etDate) {
if (stDate && etDate) {
var endOfLeaseDate = moment(etDate, "MM/DD/YYYY");
var startOfLeaseDate = moment(stDate, "MM/DD/YYYY");
dateRange(startOfLeaseDate, endOfLeaseDate);
}
}
function dateRange(stDate, etDate) {
var dates = [];
var now = stDate.clone();
var day = stDate.date();
while(now.isBefore(etDate)) {
//deal with variable month end days
var monthEnd = now.clone().endOf("month");
if (now.date() < day && day <= monthEnd.date()) { now.date(day); }
dates.push(now.format("YYYY-MM-DD"));
now = now.clone().add({ "months" : 1 });
}
console.log(dates);
}
function RunLedgerAndPV() {
var stDate = "12/31/2018";
var etDate = "12/31/2019";
createLedger(stDate, etDate);
}
RunLedgerAndPV();
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
for (var i=0; now <= endDate; i++) {
dates.push(new Date(now));
now = now.addMonths(1);
}
you instantiate and use i in order to loop through nothing. the condition now <= endDate is in no way affected by the value of i ( typically you increment / decrement i until it reaches the desired value as : var i=0; i < 11; i++ ) i dont event know how this would work, my first instinct is that it will generate a loop that wont stop until until we reach that endDate date.
You seems to be looking for getting all the date between a specific range, try the following :
var enumerateDaysBetweenDates = function(startDate, endDate) {
var dates = [];
var currDate = moment(startDate, 'MM/DD/YYYY');;
var lastDate = moment(endDate, 'MM/DD/YYYY');;
while(currDate.add(1, 'months').diff(lastDate) < 0) {
console.log(currDate.toDate());
dates.push(currDate.clone().toDate());
}
return dates;
};
I'm trying to get the diference between 2 dates that look like this:
2018/10/05 13:59
But my issue is with my code, it always retunr NaN.
This is my current code:
var start = '2018/10/05 13:59';
var end = '2018/10/05 17:59';
var converted_start = start.replace("/", "-");
var converted_end = end.replace("/", "-");
// end - start returns difference in milliseconds
var diff = new Date(converted_end - converted_start);
// get days
var days = diff/1000/60/60/24;
alert(days);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I tried to replace the / with - in my code but that didn't fix the issue!
Could someone please advice on this issue?
Thanks in advance.
var start = '2018/10/05 13:59';
var end = '2018/10/05 17:59';
var startDate = Date.parse(start);
var endDate = Date.parse(end);
var diff = new Date(endDate - startDate);
var days = diff/1000/60/60/24;
this works for me
You can use the following to get days difference in two dates format (YYYY/MM/DD hh:mm):
var start = new Date('2018/10/05 13:59');
var end = new Date('2018/10/05 17:59');
// get hours
var hours= (end-start)/3600000;
alert(hours);
I read in the documentation of moment.js that if you want to add 1 month to the current date, you can use this code:
var moment = require('moment');
var futureMonth = moment().add(1, 'M').format('DD-MM-YYYY');
But the problem is that this does not add the way I'm expecting it to. For example, let's say the current date is 31/10/2015 (the last day in the month of October). In code:
var currentDate = moment().format('DD-MM-YYYY');
var futureMonth = moment().add(1, 'M').format('DD-MM-YYYY');
console.log(currentDate) // Result --> 31/10/2015
console.log(futureMonth) // Result --> 30/11/2015
If you take a look at the calendar date, 1 month/ 31 days from 31/10/2015 should be 1/12/2015 (the first day of December), not 30/11/2015 (the last day of November).
Could anyone help me fix this problem?
var currentDate = moment('2015-10-30');
var futureMonth = moment(currentDate).add(1, 'M');
var futureMonthEnd = moment(futureMonth).endOf('month');
if(currentDate.date() != futureMonth.date() && futureMonth.isSame(futureMonthEnd.format('YYYY-MM-DD'))) {
futureMonth = futureMonth.add(1, 'd');
}
console.log(currentDate);
console.log(futureMonth);
DEMO
EDIT
moment.addRealMonth = function addRealMonth(d) {
var fm = moment(d).add(1, 'M');
var fmEnd = moment(fm).endOf('month');
return d.date() != fm.date() && fm.isSame(fmEnd.format('YYYY-MM-DD')) ? fm.add(1, 'd') : fm;
}
var nextMonth = moment.addRealMonth(moment());
DEMO
According to the latest doc you can do the following-
Add a day
moment().add(1, 'days').calendar();
Add Year
moment().add(1, 'years').calendar();
Add Month
moment().add(1, 'months').calendar();
startDate = "20.03.2020";
var newDate = moment(startDate, "DD-MM-YYYY").add(5, 'days');
console.log(newDate)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
You could try
moment().add(1, 'M').subtract(1, 'day').format('DD-MM-YYYY')
I am trying to know if a certain timestamp belongs to today, but I'm getting lost in Javascripts date management.
Is there any way to check if a timestampo belongs to the current day?
Simple check 1st timestamp of both days and compare them.
var ts = 1564398205000;
var today = new Date().setHours(0, 0, 0, 0);
var thatDay = new Date(ts).setHours(0, 0, 0, 0);
if(today === thatDay){
console.log("*** Same day ***");
}
It seems nasty-ish to me however you could do something similar to:
function isInToday(inputDate)
{
var today = new Date();
if(today.setHours(0,0,0,0) == inputDate.setHours(0,0,0,0){ return true; }
else { return false; }
}
This assumes you've already set your input date as a JS date. This will check if the two dates occur on the same day, and return true if so and false if not.
I'm sure someone will come along with a neater way to do this or a case where this fails but as far as I can see this should do the trick for you.
you can really depend on ISO date string with a substr function to compare the two strings
var T=1479288780873; /*assume your timestamp value*/
var theDay=new Date(T);
var today=new Date;
theDay.toISOString().substr(0,10) == today.toISOString().substr(0,10) ? console.log("same day"):null;
You can do something like this :
var day = 24 * 60 * 60 * 1000; //nb millis in a day
var todayTimestamp = new Date(year, month, day).getTime(); // Be careful month is 0 start
//OR
var todayTimestamp = new Date().setHours(0,0,0,0).getTime();
var diff = myTimestamp - todayTimestamp;
if ( diff >= 0 && diff <= day ) {
console.log("timestamp is today");
else {
console.log("timestamp is not today");
}
var timestamp = '2016-11-16 03:14:07.999999';
var datestamp = timestamp.substring(0, 10);
Date.prototype.yyyymmdd = function() {
var mm = this.getMonth() + 1;
var dd = this.getDate();
return [this.getFullYear(), mm, dd].join('-');
};
var date = new Date();
date.yyyymmdd();
console.log(String(datestamp) === String(date.yyyymmdd()));
It depends what format your timestamp is in.
But here is the most basic way to achieve this:
var today = new Date(year, month, day);
var timestamp = //your timestamp;
if (timestamp == timestamp){ //make sure the date formats are the same
//your code
}
I hope this is what you were looking for, there are more methods with the javascript date reference, don't hesitate to look it up.
I have two dates namely newdate and haha. newdate will be today's date (current date) and haha date can be any.The below code is not working for me as i have provided
newdate : 07-Feb-2014 10:04
haha :03-Feb-2014 00:00
its always coming to else part
sdate:03-Feb-2014
stime :00:00
var haha=sdate+" "+stime;
var newdate=new Date();
var date_str = moment(newdate).format("DD-MMM-YYYY HH:mm");
alert(date_str);
if (Date.parse(haha) < Date.parse(date_str)) {
alert("Start date cannot be less than today's date");
return false;
}
else {
alert("hahahhahaha");
}
NOTE I am using moment with langs javscript
Your Code Works. Stime is formatted wrong remove the colon from in front of the first set of 00. stime 00:00. How are you generating stime this is the cause of you problem?
You can see my test here.
var sdate = "03-Feb-2014";
var stime = "00:00";
var haha = sdate + " " + stime;
var newdate = new Date();
if (navigator.appName.indexOf("Internet Explorer") != -1) {
alert("isIE");
var dateObject = (parseISO8601(haha));
var hahaDate = new Date(dateObject.year, dateObject.month, dateObject.day, dateObject.hour, dateObject.min);
alert(hahaDate);
if (hahaDate.getTime() < newdate.getTime()) {
alert("Start date cannot be less than today's date");
return false;
} else {
alert("hahahhahaha");
}
} else {
var date_str = moment(newdate).format("DD-MMM-YYYY HH:mm");
alert(date_str);
if (Date.parse(haha) < Date.parse(date_str)) {
alert("Start date cannot be less than today's date");
return false;
} else {
alert("hahahhahaha");
}
}
function parseISO8601(dateStringInRange) {
var dateAsObject = {};
var splitTimeFromDate = dateStringInRange.split(" ");
var splitTimeValues = splitTimeFromDate[1].split(":");
dateAsObject.hour = splitTimeValues[0];
dateAsObject.min = splitTimeValues[1];
var splitDate = splitTimeFromDate[0].split("-");
dateAsObject.year = splitDate[2];
dateAsObject.day = splitDate[0];
dateAsObject.month = monthToNum(splitDate[1]);
return dateAsObject;
}
function monthToNum(month) {
if (month == "Feb") return 1;
}
[Edit: Ok sorry I messed up with the Colon, If it fails at the else are you sure you unit tests include enough scenario to were the date is both greater than and less than the current date if it is only less than like your example you will never hit the code in the else. Again the code just works don't know what to say :-(, update example for both situations]
[Edit: Here is an example not complete you have to remember javascript is not universal. When you ask a question about JS assume as DEVs we all use Chrome or FF, or atleast post the browser(s) you tired. I provided a simple example of how I would accomplish this. Frankly I don't like external framework when I can do it myself so as you can see I am not using it feel free to do what you want the issue is cause by the way IE Parses DateTime you must use a more universal format like the one provided below. Example of possible formats: http://www.w3schools.com/jsref/jsref_obj_date.asp. Anyhow GL]
That is a bit convoluted, consider:
var newdate = new Date();
var date_str = moment(newdate).format("DD-MMM-YYYY HH:mm");
Date.parse(date_str);
if the above works (and there is absolutely no guarantee that Date.parse will correctly parse the string in all browsers in use), then all of that is equivalent to:
var newdate = new Date();
newdate.setSeconds(0, 0);
You would do very much better to manualy parse haha (or use moment.js since you have it already) and compare the resultant date objects.
Consider:
// s is dd-mmm-yyyy hh:mm
function stringToDate(s) {
s = s.split(/[- :]/);
var months = {'jan':0, 'feb':1, 'mar':2, 'apr':3, 'may':4, 'jun': 5,
'jul':6, 'aug':7, 'sep':8, 'oct':9, 'nov':10, 'dec':11};
return new Date(s[2], months[s[1].toLowerCase()], s[0], s[3], s[4], 0, 0);
}
var newdate = '07-Feb-2014 10:04';
var haha = '03-Feb-2014 00:00';
alert(stringToDate(newdate).getTime() == stringToDate(haha).getTime()); // false
// Set to same time
var newdate = '03-Feb-2014 00:00';
alert(stringToDate(newdate).getTime() == stringToDate(haha).getTime()); // true