i'm trying to translate a birth date in the "name" of the day, like monday, tuesday, etc. but i have some doubts on how to do it, i thought first : take the two timestamps (date of birth and current timestamp) and then use a "modulo" like %7 , then with the "rest" of the modulo looking through an array of names. But, actually, the timestamp is not meant to be divided by a modulo isn't it? how would you do?
Thanks
You can get the UNIX Timestamp using valueOf() function where you can use modulo but you might try using easier API to get the day name from a date. I have taken the actual date of birth, say 14 April 1983 in a timestamp format. I get the monthly date value and month value form the actual DOB. I construct another date object with the monthly-date and month value and current year's value. Then I get the weekly day value (0-6 = Sun-Sat) from this date, and show the mapped day name from the array containing the names of the days.
var days = "Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday";
var actualDOB = "04/14/1983";
var date = new Date(new Date().getFullYear(), new Date(actualDOB).getMonth(), new Date(actualDOB).getDate());
alert("The day of the week this year for your birthday is : " + days.split(',')[date.getDay()] + " (" + date.toDateString() + ")");
Hope this helps.
If you have a real Date object, you can use the getDay() method of it in combination with an array of weekdays. Same goes for months. Here's a function to return the formatted actual birthday, the original day of birth and the day for the birthday this year:
function birthDAY(dat){
var result = {},
birthday = new Date(dat),
weekdays = 'sun,mon,tue,wedness,thurs,fri,satur'.split(','),
months = 'jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec'.split(','),
dateFormatted = function(dateobj) {
return [
weekdays[dateobj.getDay()],'day',
', ', months[dateobj.getMonth()],
' ', dateobj.getDate(),
' ', dateobj.getFullYear()
].join('');
};
result.bdformatted = dateFormatted(birthday);
result.origbd = weekdays[birthday.getDay()]+'day';
birthday.setFullYear(new Date().getFullYear());
result.bdthisyear = weekdays[birthday.getDay()]+'day');
return result;
}
//usage
var bdObj = birthDAY('1973/11/02'); // <- your timestamp here
alert(bdObj.bdformatted); //=> friday, nov 2 1973
alert(bdObj.origbd); //=> friday
alert(bdObj.bdthisyear); //=> wednessday
Related
I have a news feed and I want to display the time an article is published simply as Today, Yesterday, 2 days, 3 days ago, etc. I just want to preserve the YYYY-MM-DD format and get rid of the timezone part. However at 8pm NYC Eastern Time (ET) the dates change for example from 2 days ago to 3 days ago. How can I make sure that this change is only made at midnight ET every day?
An example of an article date:
2020-03-17T04:00:00.000Z
Current code:
convertDateLiteral(article_date: string) {
const newDt = article_date.split('T')[0];
let date = moment(newDt);
if (moment({hours: 0}).diff(date, 'days') >= 2) {
return date.add(1,'d').fromNow(); // '2 days ago' etc.
}
//console.log(date.calendar().split(' ')[0])
return date.calendar().split(' ')[0]
}
Given dates strings in ISO 8601 format, you can convert to Date objects, zero the time, then compare to today's date with zeroed time and rounding for daylight saving changes, if any. E.g.
function getEvenDaysDiff(d) {
let now = new Date();
now.setHours(0,0,0,0);
let then = new Date(d);
then.setHours(0,0,0,0);
return Math.round((now - then) / 8.64e7);
}
function parseAndFormatDate(d) {
d = new Date(d);
let z = n => (n<10?'0':'')+n;
return d.getFullYear() + '-' +
z(d.getMonth()+1) + '-' +
z(d.getDate());
}
// test - dates are UTC so local dates may differ
let dates = [
'2020-03-17T04:00:00.000Z',
'2020-03-16T14:00:00.000Z',
'2020-03-12T04:30:00.000Z',
'2020-02-17T12:00:00.000Z'
].forEach(
s => console.log(parseAndFormatDate(s) + ' ' + getEvenDaysDiff(s) + ' days ago.')
);
Note that as the timestamps are UTC, the date they represent may be different to the equivalent local date. I've assumed you want differences to local dates. If you want UTC, then use UTC methods in getEvenDaysDiff and the parseAndFormatDate function is superfluous.
I am looking to do something quite complex and I've been using moment.js or countdown.js to try and solve this, but I think my requirements are too complex? I may be wrong. Here is the criteria...
I need to be able to have the following achievable without having to change the dates manually each year, only add it once and have many countdowns on one page.
Find current date
Find current year
Find current month
Find day within week of month that applies
¬ 3rd Sunday or 2nd Saturday
Convert to JS and output as html and run countdown
When past date - reset for following year
Pretty mental. So for example if an event is always on the 3rd Sunday of March. The date would not be the same each year.
2016 - Sunday March 19th
2017 - Sunday March 20th
2018 - Sunday March 18th etc.
I hope this is explained well, I realise it may be a total mess though. I managed to get it resetting each year with the date added manually but then someone threw in the spanner of the date being different each year.
var event = new Date();
event = new Date(event.getFullYear() + 1, 3 - 1, 19);
jQuery('#dateEvent').countdown({ until: event });
<div id="dateEvent"></div>
I have edited this answer as I have now put together a solution that works for me. As I believe this isn't simple coding due to the fact it wasn't actually answered 'Please, this is basic coding. pick up a javascript book and learn to code', yeah thanks...
// get the specific day of the week in the month in the year
function getDay(month) {
// Convert date to moment (month 0-11)
var myMonth = moment("April", "MMMM");
// Get first Sunday of the first week of the month
var getDay = myMonth.weekday(0); // sunday is 0
var nWeeks = 3; // 0 is 1st week
// Check if first Sunday is in the given month
if (getDay.month() != month) {
nWeeks++;
}
// Return 3rd Sunday of the month formatted (custom format)
return getDay.add(nWeeks, 'weeks').format("Y-MM-D h:mm:ss");
}
// print out the date as HTML and wrap in span
document.getElementById("day").innerHTML = '<span>' + getDay() + '</span>';
Using
<script src="moment.js"></script>
Hope it helps someone - I'll update when I figure how to + 1 year after it's checked current date and event has passed. I'll look in that JS book.
Please take a look at the below code, I explained in the comment what what does.
You use it by supplying a javascript Date object of any wished start date, and then add as a second value the corresponding year you wish to know the date in.
var date = new Date("2016-03-20");
function getDayInYear(startDate, year) {
// get a moment instance of the start date
var start = moment(startDate);
// collect the moment.js values for the day and month
var day = start.day();
var month = start.month();
// calculate which week in the month the date is.
var nthWeekOfMoth = Math.ceil(start.date() / 7);
// Build up the new moment with a date object, passing the requested year, month and week in it
var newMoment = moment(new Date(year,month,(nthWeekOfMoth * 7)));
// Return the next instance of the requested day from the current newMoment date value.
return newMoment.day(day);
}
var oldMoment = moment(date);
var newMoment2017 = getDayInYear(date,2017);
var newMoment2018 = getDayInYear(date,2018);
console.log(oldMoment.format('YYYY MMMM dddd DD'));
console.log(newMoment2017.format('YYYY MMMM dddd DD'));
console.log(newMoment2018.format('YYYY MMMM dddd DD'));
/** working from today up to 10 years into the future **/
var date = new Date();
var year = date.getFullYear();
for(var i = 0; i < 11; i++) {
console.log(getDayInYear(date, year+i).format('YYYY MMMM dddd DD'));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>
I have "startdate" field, that I'm getting its value. Plus I have three other fields: day,month,year. Which I'm also getting its values. Now I have to add day and month and year to startdate to get my new date. Can anybody help me with this, in order to maintain date conditions? e.g: so i don't add 12 days to 25 and get 37.
function calDate(){
var startDate;
var trs_jour = Ext.getCmp('JOUR').getValue();
var trs_mois = Ext.getCmp('MOIS').getValue();
var trs_annee = Ext.getCmp('ANNEE').getValue();
if(trs_jour!='' || trs_mois!='' || trs_annee!=''){
var d = new Date(Ext.getCmp('STARTDATE').getValue());
var year = d.getFullYear();
var month = d.getMonth()+1;
var day = d.getDate();
}
Ext.Date class defines some basic methods for handling dates.
Provides a convenient method for performing basic date arithmetic. This method does not modify the Date instance being called - it creates and returns a new Date instance containing the resulting date value.
Ext.Date.add ( date , interval , value )
PARAMETERS
date : Date
The date to modify
interval : String
A valid date interval enum value.
value : Number
The amount to add to the current date.
RETURNS : Date
The new Date instance.
Examples :
// Basic usage:
var dt = Ext.Date.add(new Date('10/29/2006'), Ext.Date.DAY, 5);
console.log(dt); // returns 'Fri Nov 03 2006 00:00:00'
// Negative values will be subtracted:
var dt2 = Ext.Date.add(new Date('10/1/2006'), Ext.Date.DAY, -5);
console.log(dt2); // returns 'Tue Sep 26 2006 00:00:00'
I have to compare the date that they want to put in and the current date today, and if they have put in a date that is in the future, then alert them to change the date, otherwise insert the data.
Basically I am having issues comparing the dates. here is my code:
var today = year + '-' + month + '-' + day + ' 00:00:00';
var d1 = new Date(postdate); // postdate = 2014/02/01 ie: 1 Feb 2014
var d2 = new Date(today); // todays date
if(d1>d2){
alert('You cannot post in the future!');
}
But that doesnt seem to work. Where am I going wrong?
Convert the dates into a comparable number, like milliseconds.
if(d1.valueOf()>d2.valueOf()){
alert('You cannot post in the future!');
}
You don't need to create a new variable today.
If by today you are trying to get today's date, you can simply do
var today = new Date();
var d1 = new Date(postdate); // postdate = 2014/02/01 ie: 1 Feb 2014
//----------
var d2 = new Date(year,month,day); // todays date
//----------
if(d1>d2){
alert('You cannot post in the future!');
}
Remember month is 0 based index. So, for december it would be 11.
Compare the dates with the same format, if today is 2014-01-24 00:00:00 then postdate also should be 2014-02-01 00:00:00
Then use + prefix to compare milliseconds:
if(+d1 > +d2){
alert('You cannot post in the future!');
}
How can I create a date object which is less than n number of months from another date object? I am looking for something like DateAdd().
Example:
var objCurrentDate = new Date();
Now using objCurrentDate, how can I create a Date object having a date which is six months older than today's date / objCurrentDate?
You can implement very easily an "addMonths" function:
function addMonths(date, months) {
date.setMonth(date.getMonth() + months);
return date;
}
addMonths(new Date(), -6); // six months before now
// Thu Apr 30 2009 01:22:46 GMT-0600
addMonths(new Date(), -12); // a year before now
// Thu Oct 30 2008 01:20:22 GMT-0600
EDIT: As reported by #Brien, there were several problems with the above approach. It wasn't handling correctly the dates where, for example, the original day in the input date is higher than the number of days in the target month.
Another thing I disliked is that the function was mutating the input Date object.
Here's a better implementation handling the edge cases of the end of months and this one doesn't cause any side-effects in the input date supplied:
const getDaysInMonth = (year, month) => new Date(year, month, 0).getDate()
const addMonths = (input, months) => {
const date = new Date(input)
date.setDate(1)
date.setMonth(date.getMonth() + months)
date.setDate(Math.min(input.getDate(), getDaysInMonth(date.getFullYear(), date.getMonth()+1)))
return date
}
console.log(addMonths(new Date('2020-01-31T00:00:00'), -6))
// "2019-07-31T06:00:00.000Z"
console.log(addMonths(new Date('2020-01-31T00:00:00'), 1))
// "2020-02-29T06:00:00.000Z"
console.log(addMonths(new Date('2020-05-31T00:00:00'), -6))
// "2019-11-30T06:00:00.000Z"
console.log(addMonths(new Date('2020-02-29T00:00:00'), -12))
// "2019-02-28T06:00:00.000Z"
Create date object and pass the value of n, where n is number(add/sub) of month.
var dateObj = new Date();
var requiredDate= dateObj.setMonth(dateObj.getMonth() - n);
var oldDate:Date = new Date();
/*
Check and adjust the date -
At the least, make sure that the getDate() returns a
valid date for the calculated month and year.
If it's not valid, change the date as per your needs.
You might want to reset it to 1st day of the month/last day of the month
or change the month and set it to 1st day of next month or whatever.
*/
if(oldDate.getMonth() < n)
oldDate.setFullYear(oldDate.getFullYear() - 1);
oldDate.setMonth((oldDate.getMonth() + n) % 12);
You have to be careful because dates have a lot of edge cases. For example, merely changing the month back by 6 doesn't account for the differing number of days in each month. For example, if you run a function like:
function addMonths(date, months) {
date.setMonth((date.getMonth() + months) % 12);
return date;
}
addMonths(new Date(2020, 7, 31), -6); //months are 0 based so 7 = August
The resulting date to return would be February 31st, 2020. You need to account for differences in the number of days in a month. Other answers have suggested this in various ways, by moving it to the first of the month, or the last of the month, or the first of the next month, etc. Another way to handle it is to keep the date if it is valid, or to move it to the end of the month if it overflows the month's regular dates. You could write this like:
function addMonths(date, months) {
var month = (date.getMonth() + months) % 12;
//create a new Date object that gets the last day of the desired month
var last = new Date(date.getFullYear(), month + 1, 0);
//compare dates and set appropriately
if (date.getDate() <= last.getDate()) {
date.setMonth(month);
}
else {
date.setMonth(month, last.getDate());
}
return date;
}
This at least ensures that the selected day won't "overflow" the month that it is being moved to. Finding the last day of the month with the datePart = 0 method is documented here.
This function still leaves a lot to be desired, as it doesn't add years and you can't subtract more than a year (or you will run into a new issue with negatives being involved). However, fixing those and the other issues you may run into (namely timezones) will be left as an exercise for the reader.