$scope.articles = [
{
link: "http://google.com",
source: "Google",
title: "hello",
"date": new Date(2008, 4, 15)
},
];
<tbody>
<tr ng-repeat = "article in articles | orderBy:sortType:sortReverse | filter:searchArticle ">
<td>{{article.source}}</td>
<td>{{article.title}}</td>
<td class="date-table-td">{{article.date | date:'longDate'}}</td>
</tr>
</tbody><!-- End table body -->
Hi, I currently have this. So the date shows as May 15, 2008. How do I show only the year or only the year+month?
Thanks.
According to the documentation, you can use date.getFullYear() to get the year in YYYY format and date.getMonth() to get the month.
An example:
let list = document.getElementById('test');
let date = new Date(2008, 4, 15);
// year
let yearNode = document.createElement("li");
yearNode.appendChild(document.createTextNode(date.getFullYear()));
list.appendChild(yearNode)
// year + month
let yearMonthNode = document.createElement("li");
yearMonthNode.appendChild(document.createTextNode(date.getFullYear() + " " + date.getMonth()))
list.appendChild(yearMonthNode)
<ul id="test">
</ul>
with date.getMonth() you need +1 to this
var month = date.getMonth() + 1
Related
I have a start date 4/10/2021 and end date 4/12/2021
I want get Tuesday, Thursday and Friday date in jquery
I found this solution:
var x = new Date();
//set the financial year starting date
x.setFullYear(2021, 10, 04);
//set the next financial year starting date
var y = new Date();
y.setFullYear(2021, 12, 04);
var j = 1;
var count = 0;
//getting the all fridays in a financial year
for ( var i = 0; x<y; i += j) {
if (x.getDay() == 5) {
$("#append_text").append("Date : " + x.getDate() + "/"
+ (x.getMonth() + 1) + "<br>");
x = new Date(x.getTime() + (7 * 24 * 60 * 60 * 1000));
j = 7;
count++;
} else {
j = 1;
x = new Date(x.getTime() + (24 * 60 * 60 * 1000));
}
}
$("#append_text").append("total fridays : " + count + "<br>");
but it return only Friday and i think it doesn't work truly
The result is:
Date : 5/11
Date : 12/11
Date : 19/11
Date : 26/11
Date : 3/12
Date : 10/12
Date : 17/12
Date : 24/12
Date : 31/12
total fridays : 9
The solution link is here:
Get Friday Dates of Year in javascript using jquery
do you have any solution for that?
As mentioned in getDay() docs:
The getDay() method returns the day of the week for the specified date according to local time, where 0 represents Sunday.
So, clearly
if (x.getDay() == 5)
5 here stands for Friday. So, if you also need Tuesday as 2 & Thursday as 4, you simply need to modify for loop like:
var day = x.getDay();
if (day === 2 || day === 4 || day === 5)
Demo:
var x = new Date();
//set the financial year starting date
x.setFullYear(2021, 10, 04);
//set the next financial year starting date
var y = new Date();
y.setFullYear(2021, 12, 04);
var html = '';
var count = 0;
//getting the all fridays in a financial year
for (var i = 0; x < y; i++) {
var day = x.getDay();
if (day === 2 || day === 4 || day === 5) {
html += "Date : " + x.getDate() + "/" + (x.getMonth() + 1) + "<br>";
if (day === 5)count++;
}
x.setDate(x.getDate() + 1)
}
$("#append_text").append(html);
$("#append_text").append("total fridays : " + count + "<br>");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=append_text></div>
Try this.
var start = new Date(2021, 10, 04);
var end = new Date(2021, 12, 04);
var tuesdays = [], thursdays = [], fridays = [];
for (var current = start; current <= end; current.setDate(current.getDate() + 1)) {
var day = current.getDay();
switch (day) {
case 2: // tuesdays
tuesdays.push(formatDate(current));
break;
case 4: // thursdays
thursdays.push(formatDate(current));
break;
case 6: // fridays
fridays.push(formatDate(current));
break;
default: //other dates
break;
}
}
function formatDate(d) { // formats date to dd/mm/yyy
return d.getDate() + '/' + (d.getMonth() + 1) + '/' + d.getFullYear();
}
console.log(tuesdays.length + " Tuesdays: ", tuesdays.join('\t'));
console.log(thursdays.length + " Thursdays: ", thursdays.join('\t'));
console.log(fridays.length + " Fridays: ", fridays.join('\t'));
You can do this by iterating over every date between the two dates and saving the ones that fit some criterion, or you can get the first of the required dates, then add 7 days to get each weekly until the end date, e.g.
// Parse date in day/month/year format
function parseDMY(s) {
let [d, m, y] = s.split(/\D/);
return new Date(y, m-1, d);
}
// Get next day by dayNumber on or after date, default today
function getDayOfWeek(day, date) {
let d = date? new Date(+date) : new Date();
d.setDate(d.getDate() - d.getDay() + day +
(day < d.getDay()? 7 : 0));
return d;
}
// Format date as dd/mm/yyyy
function formatDMY(date) {
return date.toLocaleString('en-GB', {
year : 'numeric', // remove if year not required
month: '2-digit',
day : '2-digit'
});
}
// Given start and end date, get days by day number between
// dates inclusive
function getDaysBetweenDates(d0, d1, ...days){
let dStart = parseDMY(d0);
let dEnd = parseDMY(d1);
// Guard against endless loop
if (dEnd < dStart) return;
let dates = [];
while (dStart <= dEnd) {
days.forEach(day => {
let d = getDayOfWeek(day, dStart);
if (d <= dEnd) dates.push(formatDMY(d));
});
dStart.setDate(dStart.getDate() + 7);
}
return dates.sort(
(a, b) => a.split(/\D/).reverse().join('').localeCompare(
b.split(/\D/).reverse().join(''))
);
}
// Get all Tue, Thu and Fri between 4 Oct 2021 and 4 Dec 2021 inclusive
console.log(getDaysBetweenDates('4/10/2021', '4/12/2021', 2, 4, 5));
I've left the year in the date, it's easily removed by removing year: 'numeric', from the formatting options.
Note that in the OP:
y.setFullYear(2021, 12, 04);
creates a Date for 4 Jan, 2022 not 4 Dec 2021 because months are zero indexed, so December is 11. A month value of 12 rolls over to January of the following year.
Must check if a collection of projects contains a startDate that has passed 3, 6, and so on, months, using moment.js but having problems coming up with a way to calculate the difference in time between today and startDate, was thinking of seeing if (today / startDate) % 3 === 0 but I don't think that's the best way and the results are not as expected. Even using moment.js diff, like this doesn't yield desired results and logs projects that clearly haven't elapsed elapsed 3, 6 etc... months.
Obviously I'm missing something would appreciate some help thank you.
const today = moment()
const projects = await ProjectModel.find()
projects.forEach(project => {
if (today.diff(moment(project.startDate), "month") % 3 == 0) {
console.log(project)
}
})
% is the wrong way to go about it. You want to find the 3 month ago bracket that the date falls in, so get the difference in months and divide by 3 and floor the result. If diff < 3, you'll get 0. If 3 <= diff <6 months, you'll get 1, etc.
E.g.
let projects = [
{startDate: new Date(2017,10,1)}, // 1 Nov 2017
{startDate: new Date(2018,10,1)}, // 1 Nov 2018
{startDate: new Date(2019, 0,1)}, // 1 Jan 2019
{startDate: new Date(2019, 3,1)}, // 1 Apr 2019
{startDate: new Date(2019, 4,1)}, // 1 May 2019
{startDate: new Date(2019, 6,1)}, // 1 Jul 2019
{startDate: new Date(2019, 7,1)} // 1 Aug 2019
];
let today = moment();
projects.forEach(project => {
let diff = today.diff(moment(project.startDate), "month") / 3 | 0;
console.log(
moment(project.startDate).format('DD-MMM-YYYY') +
' was ' + (diff * 3) + ' to ' +
(++diff * 3) + ' months ago'
);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
The modulo makes sense to me. If you roll your own dates, it works like this (plus or minus a leap-year-day, which is what libraries like moment.js are good at abstracting away):
const projects = [
{ id: 1, startDate: 1551441600000 },
{ id: 2, startDate: 1554120000000 },
{ id: 3, startDate: 1556712000000 },
{ id: 4, startDate: 1559390400000 },
{ id: 5, startDate: 1564660800000 }
];
// Gets current year, month, and date
const now = new Date(),
thisYear = now.getFullYear(),
thisMonth = now.getUTCMonth(),
thisDate = now.getUTCDate();
// Loops through projects
projects.forEach(project => {
// Gets year, month, and date for each project
const then = new Date(project.startDate),
startYear = then.getFullYear(),
startMonth = then.getUTCMonth(),
startDate = then.getUTCDate();
//console.log(then.toUTCString());
// Reports on the project if it started on an earlier day of the month 3, 6, etc months ago
const justStarted = thisYear == startYear && thisMonth == startMonth,
isQuarterInterval = thisMonth % 3 == startMonth % 3 && thisDate >= startDate
if(isQuarterInterval && !justStarted){
console.log("Project #" + project.id + " started " + then);
}
});
I want a javascript function that gives me start_date as the last week monday date and end_date as last week sunday date.
So for example, today is 03/09/2016, so I want
start_date = 02/29/2016
end_date = 03/06/2016
so far I have wriiten the code as
function GetLastWeekDate(){
start_date = new Date();
start_date.setHours(0,0,0,0);
end_date = new Date();
var date=null;
var curr = date ? new Date(date) : new Date();
var first = curr.getDate() - curr.getDay("monday"),
last = first + 6;
start_date.setDate( first );
end_date. setDate( last );
}
(function() {
var original = Date.prototype.getDay;
var daysOfWeek = {
sunday: 0,
monday: 1,
tuesday: 2,
wednesday: 3,
thursday: 4,
friday: 5,
saturday: 6,
};
Date.prototype.getDay = function(weekBegins) {
weekBegins = (weekBegins || "sunday").toLowerCase();
return (original.apply(this) + 7 - daysOfWeek[weekBegins]) % 7;
};
})();
but its giving me date as
03/07/2016 and 03/13/2016
how do I fix this to get the dates I want?
If you have a lot of date handling to do, I can only strongly suggest that you use the moment.js library.
In this case, the dates would be :
var startDate = moment().subtract(1, 'week').startOf('week');
var endDate = moment().subtract(1, 'week').endOf('week');
Here you can see it in action :
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("fromDate").textContent = moment().subtract(1, "week").startOf("week");
document.getElementById("toDate").textContent = moment().subtract(1, "week").endOf("week");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.2/moment.min.js"></script>
<html>
<body>
<p>From : <span id="fromDate"></span></p>
<p>To : <span id="toDate"></span></p>
</body>
</html>
If in case you just want plain js solution w/out any external libraries. You can try this instead.
var dateNow = new Date();
var firstDayOfTheWeek = (dateNow.getDate() - dateNow.getDay()) + 1; // Remove + 1 if sunday is first day of the week.
var lastDayOfTheWeek = firstDayOfTheWeek + 6;
var firstDayOfLastWeek = new Date(dateNow.setDate(firstDayOfTheWeek - 7));
var lastDayOfLastWeek = new Date(dateNow.setDate(lastDayOfTheWeek - 7));
In the above solution, firstDataOfLastWeek will be previous week Monday, and lastDayOfLastWeek will be previous week Sunday.
I have inherited a form that has some existing JavaScript that creates a new date + 3 months from today's date.
var monthAway = new Date(new Date);
var day =monthAway.getDate();
var month =monthAway.getMonth() + 3;
var year =monthAway.getFullYear();
$('#Date_for_Second_Store_Access_to_Expire').val(day + "/" + month + "/" + year);
<p><input id="Date_for_Second_Store_Access_to_Expire" type="hidden" name="Date_for_Second_Store_Access_to_Expire" class="required" /></p>
Issue is that if today's date is in October, November or December new date month will be 13, 14 or 15 rather than updating the to 1, 2 or 3 and then updating the year, e.g. 5/11/2014 is 05/14/2014 rather than 05/02/2015.
Any ideas?
Try this:
var x = 3; //or whatever offset
var CurrentDate = new Date();
CurrentDate.setMonth(CurrentDate.getMonth() + x);
alert(CurrentDate);
Add 3 months to monthAway variable using setMonth method as below
monthAway.setMonth(monthAway.getMonth() + 3);
then simply use the modified monthAway to display the expiration date. Please note that getMonth() Method will return 0-11 where 0 is January, 1 is February, ... , 11 is December, so you need to do this to display the correct month
var month = monthAway.getMonth() + 1;
This is the complete modified code, the value of #Date_for_Second_Store_Access_to_Expire would be 5/2/2015 assuming the code is executed today (5/11/2014).
var monthAway = new Date(new Date);
monthAway.setMonth(monthAway.getMonth() + 3); // add 3 months to monthAway
var day = monthAway.getDate();
var month = monthAway.getMonth() + 1; // add 1 because .getMonth returns zero based month
var year = monthAway.getFullYear();
$('#Date_for_Second_Store_Access_to_Expire').val(day + "/" + month + "/" + year);
<p><input id="Date_for_Second_Store_Access_to_Expire" type="hidden" name="Date_for_Second_Store_Access_to_Expire" class="required" /></p>
This is the JSFiddle that shows the value of day + "/" + month + "/" + year from the above code: http://jsfiddle.net/jwa6o6r2/
Just do a simple check when increasing the month variable:
var month = monthAway.getMonth() + 3;
if(month > 12) //If it crosses 12, start from 1 again.
month -= 12;
Change
var month = monthAway.getMonth() + 3;
To
var month = ((monthAway.getMonth() + 3) % 12) + 1;
The ((monthAway.getMonth() + 3) % 12) will give you a number from 0 to 11. Since you want 1 - 12, that's where the + 1 comes in.
For the year issue, try the following
var year = (month <= 3 ? monthAway.getFullYear() + 1 : monthAway.getFullYear());
This will check if the month is less than or equal to 3, which would only be possible if you've wrapped around.
Example code:
var postdate = entry.published.$t;
var month1 = [1,2,3,4,5,6,7,8,9,10,11,12];
var month2 = ["Jan","Feb","Mar","Apr","Mey","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var d = postdate.split("-")[2].substring(0,2);
var m = postdate.split("-")[1];
var y = postdate.split("-")[0];
for(var u2=0; u2<month1.length; u2++){ if(parseInt(m)==month1[u2]){ m=month2[u2]; break;}}
var daystr = (showPostDate) ? '' + m + ' ' + d + ', ' + y + '' : "";
var item = '' + daystr + '';
The final product of the post date = Feb 17, 2013
I want to date format = Saturday, Feb 17, 2013
var daynames = ["Monday","Tuesday", ... "Sunday"];
If you need formatting. You could use the post date to create a Date object. Like so:
var d = new Date(2013,2,17);
and use the d value to create your own date: (https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date). See example at the bottom page of the link.
Use the following to get the day and retrieve from array:
getDay
Returns the day of the week (0-6) for the specified date according to local time.
Like so:
var day = ["Monday", "Tuesday", ....];
console.log(day[d.getDay()]);