How to get previous exact date in moment.js? - javascript

I need to get "previous August, 1" date using moment.js; as there's no "previous" method in it, how to do this?

As far as I know there's nothing in the moment api for this (yet). There was some chatter about doing something similar on a GitHub issue a while back.
So you'll probably need to do it yourself.
Last August is either this year, if it's after August or last year if it's before. You can simply test this and act accordingly. So last August is 2017:
let aug = moment("08-01", "MM-DD")
let lastAug = aug < moment() ? aug : aug.subtract(1, 'years')
console.log("Last August: ", lastAug.format("dddd DD-MM-YYYY"))
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
Last February, however, is 2018.
let feb = moment("02-01", "MM-DD")
let lastfeb = feb < moment() ? feb : feb.subtract(1, 'years')
console.log("Last February: ", lastfeb.format("dddd DD-MM-YYYY"))
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>

you can use subtract() method of momentjs
var now = moment().format("dddd DD-MM-YYYY");
var previous = moment().subtract(1, 'years').format("dddd DD-MM-YYYY");
document.write(now+"<br/>"+previous);
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>

The code below will find the first august this year. If the day has not occured yet, then it will return the first august of the previous year.
var thisYear = (new Date()).getFullYear();
var lastAugust = new Date("8/1/" + thisYear);
if(moment() < lastAugust)
lastAugust = new Date("8/1/" + (thisYear - 1));
var result = moment(lastAugust.valueOf()).format("dddd DD-MM-YYYY");
document.write(result);
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>

Related

get wrong date format javascript

I get wrong output for months that have 29,30,31th. Please help thanks.
//EFFDATE = 29/03/2017;
EFFDATE = document.mainform2.EFFDATE.value;
var dayOfDate = parseFloat(EFFDATE.substring(0,2));
var monthOfDate = parseFloat(EFFDATE.substring(3,5));
var yearOfDate = parseFloat(EFFDATE.substring(6,10));
var date1 = new Date;
var date2 = new Date;
date1.setDate(dayOfDate);
date1.setMonth(monthOfDate -1);
date1.setFullYear(yearOfDate);
console.log(date1);
For example i pick the 29th of March, the system output for date1 is friday march 01 2017.
i pick 30th of March it show friday march 02 2017
It is important to maintain a certain order when you are manipulating dates. Calling new Date will return a date object with the month February. But when you set the day to 29 using setDate, JavaScript will change the date to March, 01 as there is no February, 29 in 2017.
So you either have to set the month first, then the day. Or just use this code:
var EFFDATE = 29/03/2017;
new Date(EFFDATE.split('/').reverse().join('-'));
The setMonth method has an optional second parameter for the day of the month. If it's absent, getDate() is used, and the date is still incomplete.
So this should solve the issue:
date1.setMonth(monthOfDate-1, dayOfDate);
date1.setFullYear(yearOfDate);
Wrong but I'll leave it here for posterity
The second parameter to substring should be the number of characters you want not the index.
If you debugged this and looked at the value of EFFDATE.substring(3,5) you'd see 03/20 not 03 as you were probably thinking.
var dayOfDate = parseFloat(EFFDATE.substring(0,2));
var monthOfDate = parseFloat(EFFDATE.substring(3,5));
var yearOfDate = parseFloat(EFFDATE.substring(6,10));
should be:
var dayOfDate = parseFloat(EFFDATE.substring(0,2));
var monthOfDate = parseFloat(EFFDATE.substring(3,2));
var yearOfDate = parseFloat(EFFDATE.substring(6,4));
UPDATE
I was thinking of substr rather than `substring which is subtley different.

Get particular days from date range using javascript

I will provide two dates, as a range e.g 5th Oct 2016 to 5th December 2016, And 5th Oct was Wednesday so return me all the Wednesdays till 5th December 2016.
How can this be possible using Javascript or AngularJS ?
Though not completely sure what you want to do, I think this will give you enough to work with:
var startdate = new Date("2016-10-05");
var enddate = new Date("2016-12-05");
var wednesdays = [];
while (startdate <= enddate) {
wednesdays.push(startdate);
// add a week
startdate = new Date(startdate.setDate(startdate.getDate() + 7));
}
console.log(wednesdays);

Javascript Date() is changing the date

I'm pulling events from google calendar.
I'm able to see an event date:
var date = when.split("T")[0];
console.log(date);
This outputs 2016-01-07. Then I put it into an array inside an object:
allEvents.push({
eventDate:date,
eventTime:time,
eventTBD:TBD
});
Then, when I go to grab the date again:
$.each(allEvents, function(i, v){
var eventDate = new Date(v.eventDate);
if(eventDate > startDate && eventDate < endDate){
console.log(v.eventDate);
console.log("Show This Date: " + eventDate);
}
});
For January, I get this output:
2016-01-07
Show This Date: Wed Jan 06 2016 19:00:00 GMT-0500 (EST)
for March, I get this output:
2016-03-19
Show This Date: Fri Mar 18 2016 20:00:00 GMT-0400 (EDT)
It's showing the day before the date I just showed... It seems to be 5 hours off? Do I need to account for this? How do I do so?
I know this is old, but may help somebody.
I solved this issue by adding the time on the Date argument:
var eventDate = new Date(v.eventDate + ' 00:00:00');
You can remove it after
The default timezone when parsing a date is UTC. If you want to use the client timezone you can adjust the date so that it occurs at the right time in the browser's timezone:
var eventDate = new Date(v.eventDate);
var ms_per_minute = 60000;
eventDate.setTime( eventDate.getTime() + eventDate.getTimezoneOffset()*ms_per_minute );
Otherwise you can just use UTC whenever you display the date:
console.log("Show This Date: " + eventDate.toUTCSTring() );
I think moment.js could help you on date manipulation.
Here is a fiddle for u
jQuery(document).ready(function($) {
var the_date_string = $('#in-date > pre').text();
var result = moment(the_date_string, 'YYYY-MM-DD'); //here is more info about that http://momentjs.com/docs/#/parsing/string-format/
$('#out-date > pre').text(result);
});
body {
font-family: arial;
}
<script src="http://momentjs.com/downloads/moment.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="in-date"> INPUT: <pre>2016-01-07</pre></h1>
<h1 id="out-date"> OUTPUT: <pre></pre></h1>
Thumbs up if u liked it! :)
[EDIT]
If u just want the client timestamp (in internationals formats) you can easly use the moment() function

Comparing two dates in different timezones

I'm comparing two dates; one returned as a UTC String (as part of an Ajax response) and the second in local browser time:
Basically, I want to see if the date returned (endTime) happened before right now. My code is below and I thought I had it right but it's not working.
var isActive = true;
var buffer = 30000; // 30 seconds
var endTime = new Date(Date.parse(response.endTime)); // Fri Oct 23 2015 12:01:14 GMT-0400 (EDT)
var now = new Date(); // Thu Oct 22 2015 20:01:31 GMT-0400 (EDT)
var nowUtc = new Date(now).toUTCString(); // "Fri, 23 Oct 2015 00:01:31 GMT"
var nowTimeMs = new Date(nowUtc).getTime(); // 1445558491000
var endTimeMs = endTime.getTime() + buffer; // 1445616104000
if( nowTimeMs > endTimeMs ){
isActive = false;
}
isActive should remain as true but instead it's false. I feel like I've been looking at this too long and am missing something very simple. Am I?
Thanks for any helpful tips.
Update:
Based on the responses I thought I'd update my question. What is the best way to compare two dates where one is this:
new Date(); // Thu Oct 22 2015 21:51:53 GMT-0400 (EDT)
...and the other is a String representation of date:
"2015-10-23 01:49:27"
I figure the best way to create a valid Date object out of the String is using this code.
isThisActive:function(p){
var isActive = true;
var buffer = 30000;
var pEndTime = myObj.parseStringAsDate(p.callEndTime);
var now = new Date();
var offset = now.getTimezoneOffset() * 60000;
now.setTime( now.getTime() + offset );
var nowTimeMs = now.getTime();
var endTimeMs = pEndTime.getTime() + buffer;
if( nowTimeMs > endTimeMs ){
isActive = false;
}
return isActive;
},
parseStringAsDate:function(str){
var dateTimeStr = str.split(" ");
var dateStr = dateTimeStr[0].split("-");
var year = dateStr[0];
var month = dateStr[1];
var day = dateStr[2];
var timeStr = dateTimeStr[1].split(":");
var hours = timeStr[0];
var minutes = timeStr[1];
var seconds = timeStr[2];
return new Date( year,month,day,hours,minutes,seconds);
}
Because "pEndTime" is in UTC I applied the offset to the "now" Date object but even this is not working. Where's the problem here? I thought this would solve it.
SOLVED:
The latest code I posted did work. I was just getting incorrect values for the response.endTime (It wasn't converted to correct military time). Thank you everyone for your input. I've tried to upgrade as many helpful responses as I could.
You should not use the Date constructor or Date.parse (which do the same thing) to parse date strings. Either write your own parse function (below) or use a well maintained library.
To parse the format in the OP, you can use:
// Parse Thu Oct 22 2015 20:01:31 GMT-0400 (EDT)
function parseMMMDY(s) {
var b = s.split(/\W/);
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};
var sign = /GMT-\d{4}/i.test(s)? 1 : -1;
var min = +b[5] + (sign * b[8].slice(0,2) * 60 ) + (sign * b[8].slice(-2));
return new Date(Date.UTC(b[3], months[b[1].toLowerCase().slice(0,3)], b[2], b[4], min, b[6]));
}
document.write(parseMMMDY('Thu Oct 22 2015 20:01:31 GMT-0400 (EDT)'));
I think the problem is here:
var endTime = new Date(Date.parse(response.endTime));
respnonse.endTime is UTC, right? But when you parse it to Date value, Date.parse assumes it is in local timezone (GMT-0400 as in your example code). It means that the endDate gets the wrong value
I usually use moment.js in my projects which related to formatting date time, especially in the reports (I'm working in the field of finance). You must have one more library in your project but it provides many other functionalities
Sorry, this is for your new update. I haven't got enough 'population' to leave a comment :P
var endTime = new Date(Date.parse(response.endTime)); // Fri Oct 23 2015 12:01:14 GMT-0400 (EDT)
var now = new Date(); // Thu Oct 22 2015 20:01:31 GMT-0400 (EDT)
Your endTime doesn't seem to return a UTC date as you mentioned. It looks to be using (EDT) so maybe you didn't have to convert it to UTC.

Javascript getDay returning incorrect values for April, June, September, November

I'm using this script located here: http://www.javascriptkit.com/script/script2/dyndateselector.shtml
If you try it, and go to any of April, June, September or November, you will notice that the day of the week columns are incorrect. Here's a list of incorrect data (the x starts y stuff is showing the following month.)
Bugged months:
4/April (starts Sunday instead of Friday)
May starts Sunday
6/June (starts Friday instead of Wednesday)
July starts Friday
9/September (starts Saturday instead of Thursday)
October starts Saturday
11/November (starts Thursday instead of Tuesday)
December starts Thursday
You'll notice that every bugged month is starting with the day of the following month, yet all the other months seem to be correct.
I can't find anything on this problem. Anyone able to help? The actual Javascript alone can be found here, and the getDay() method occurs on line 125: http://pastebin.com/0zuBYrzv
I've tested in both Firefox and Chrome.
Here's some very simple code to demonstrate the issue:
<script>
var d = new Date();
d.setMonth(5);
d.setFullYear(2011);
d.setDate(1);
alert(d.getDay());
</script>
This will create an alert with the message "5", meaning Friday (5+1 = 6, Friday is the 6th day of the week,) when in fact Wednesday is the start of the week.
This is actually pretty interesting as i am guessing that tomorrow your original code will work as you want again.
What i think is happening is you are creating a new Date and that will automaticly initialize to today (31th of may).
Then you set the Month to June by which you basically say make it 31th of June. This date doesn't exist so javascript will turn it into 1th of July.
Finally you set the Date but since your month is not anymore what you want it to be the results will be wrong.
Looks like 0 is january and 11 is december.
Apparently JavaScript doesn't like it if I set the month, full year, then day. What I must do is set them all in one function, like so:
<script>
var d = new Date();
d.setFullYear(2011, 5, 1);
alert(d.getDay());
</script>
I think this is a bug in Javascript's Date Object.
Please take a look at the following code.
(I'm using w3school's JSref tool online to see it quickly.)
Please note, the ways used below are told by w3 schools themselves.
Some examples of instantiating a date:
var today = new Date()
var d1 = new Date("October 13, 1975 11:13:00")
var d2 = new Date(79,5,24) (//THIS IS WRONG - unexpected results!!!)
var d3 = new Date(79,5,24,11,33,0)
So please be careful when using this Date object, looks like certain ways of instantiating dates are better than others.
<script type="text/javascript">
function whatDayIsToday(date)
{
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
document.write("Today is " + weekday[date.getDay()] + ", <br />");
document.write("the " + date.getDay() + getSuffix(date.getDay()) + " day of the week. <br /><br />")
}
function getSuffix(num)
{
return (num>3)?"th":(num==3)?"rd":(num==2)?"nd":(num==1)?"st":"";
}
//CORRECT
var d3 = new Date("01/01/2011");
whatDayIsToday(d3);
//CORRECT
var d2 = new Date("01/01/2011");
whatDayIsToday(d2);
//DOESN'T WORK
var d5 = new Date("1-1-2011");
whatDayIsToday(d5);
//WRONG
var d4 = new Date("2011", "01", "01");
whatDayIsToday(d4);
//DAY OF WEEK IS WRONG
var d = new Date(2011, 1, 1);
whatDayIsToday(d);
//DAY OF WEEK IS ALSO WRONG
var d0 = new Date(11, 1, 1);
whatDayIsToday(d0);
</script>
outputs (all using some format of 1/1/2011) are:
Today is Saturday,
the 6th day of the week. (CORRECT, January first this year was a saturday)
Today is Saturday,
the 6nd day of the week. (CORRECT)
Today is undefined,
the NaNnd day of the week. (WRONG FORMATTING, DOESN'T WORK - EXPECTED)
Today is Tuesday,
the 2nd day of the week. (WRONG - UNEXPECTED)
Today is Tuesday,
the 2nd day of the week. (WRONG - UNEXPECTED)
Today is Wednesday,
the 3nd day of the week. (WRONG - UNEXPECTED)
Based on the other answers to this question, I'm guessing it has to do with the day I'm on currently (8/26/2011) - this would be my starting new Date() and the days and/or years getting applied in the wrong order.
However, it sure would be nice if this thing worked!
This is the typical wrong approach:
var days = ["Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag"];
var d = new Date();
d.setFullYear(selectYear.options[selectYear.selectedIndex].value);
d.setMonth(selectMonth.options[selectMonth.selectedIndex].value-1);
d.setDate(selectDay.options[selectDay.selectedIndex].value);
alert(days[d.getDay()]);
It will work most of the time. But it will have problems with when current date is 31 and when trying to set date to 31 for when set at a month with less than 31 days.
This is a good way:
var days = ["Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag"];
var d = new Date(0); // solves all problems for existing dates
d.setFullYear(selectYear.options[selectYear.selectedIndex].value);
d.setMonth(selectMonth.options[selectMonth.selectedIndex].value-1);
d.setDate(selectDay.options[selectDay.selectedIndex].value);
if( d.getDate() == selectDay.options[selectDay.selectedIndex].value ) {
alert(days[d.getDay()]);
}
else {
alert("this date doesn't exist"); // date was changed cuz date didn't exist
}
Constructing the date with new Date(0) sets the date to 1 jan, this is good because the date is not 31st and january has 31 days which give us the space we need. It wont fail on the 31st and we don't need to set the datas in any special order. It will always works.
If the user sets month to september (30 days) and date to 31 the data object will hold either 1 oct or 1 sep (depending on which order you set them in). Which is irrelevant because they are both wrong. A simple check if the date is what we set it to will tell us if the date is a existing date, if not we can tell the user this.

Categories