I have a moment data object, what i want to do is get the date number, like if 2018-12-31 is given, it should return 365.
What I've currently done is this, but I feel like this is a more brute force approach since I have to run this function over and over again. Is there a more elegant way of doing this through the momentjs library?
var day = 25;
var mon = 12;
var year = 2018;
var sum = 0;
var days = 0;
var month_day = [31,28,31,30,31,30,31,31,30,31,30,31];
for ( var i = 0; i < mon; i++){
sum += month_day[i];
}
days = sum - (month_day[mon-1] - day);
console.log(days)
You can use the dayOfYear() function:
const day = 25;
const month = 12 - 1; // months are 0-based when using the object constructor
const year = 2018;
const date = moment({day, month, year});
console.log(date.dayOfYear()); // 359
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
You can do it without momentjs
let year = 2018;
let month = 12 - 1;
let day = 25;
let dayOfYear = (Date.UTC(year, month, day) - Date.UTC(year, 0, 1)) / 86400000 + 1;
console.log(dayOfYear);
The moment documentation is helpful: https://momentjs.com/docs/#/get-set/day-of-year/
var day = 25;
var mon = 12;
var year = 2018;
console.log(moment().year(year).month(mon).date(day).dayOfYear());
Related
I have a problem getting the current week date in javascript. I wrote the following code to get the current week's date, It was working well but it seems it sometimes returns the next week's date. I could not understand where is the problem.
any help would be appreciated.
This is my code:
let curr = new Date();
let week = [];
for (let i = 1; i <= 7; i++) {
let first = curr.getDate() - curr.getDay() + i;
let day = new Date(curr.setDate(first)).toISOString().slice(0, 10);
week.push(day);
};
console.log(week)
The output:
['2022-06-13', '2022-06-14', '2022-06-15', '2022-06-16', '2022-06-17', '2022-06-18', '2022-06-19']
but today's date is 6/12/2022, but the above date started from 13/06/2022
Source:
here
When you do +i you are adding numbers 1 to 7 to your first variable. Now since the week starts from Sunday=0, you do not need to add an offset.
Just iterate loop from 0 to 6:
let curr = new Date(new Date().getTime() - (7 * 24 * 60 * 60 * 1000));
let week = [];
for (let i = 0; i < 7; i++) {
let first = curr.getDate() - curr.getDay() + i;
let day = new Date(curr.setDate(first)).toISOString().slice(0, 10);
week.push(day);
};
console.log(week)
[Edit] : If you want to get from 7 days ago, you can change how you initialize your curr variable.
From this :
let curr = new Date();
to this:
let curr = new Date(new Date().getTime() - (7 * 24 * 60 * 60 * 1000));
I use the getTime() method to get the epoch of today's date and subtract exactly the milliseconds passed in 7 days (or 1 week).
If I understand your question correctly, you must take into consideration when current day is sunday to get current week first day (monday).
let curr = new Date();
let week = [];
for (let i = 1; i <= 7; i++) {
let first = curr.getDate() - curr.getDay() + i;
if (curr.getDay() === 0){
first = curr.getDate() - 6;
}
let day = new Date(curr.setDate(first)).toISOString().slice(0, 10);
week.push(day);
};
console.log(week)
Start the for loop from 0
Like so
let curr = new Date();
let week = [];
for (let i = 0; i < 7; i++) {
let first = curr.getDate() - curr.getDay() + I;
let day = new Date(curr.setDate(first)).toISOString().slice(0, 10);
week.push(day);
};
console.log(week)
Remember, if you start from 1 and add 1 to the current date it will return tomorrow, and if you add 0 to today it retustns this date.
You can use moment.js library
let week = [];
let firstDayOfWeek = moment().startOf('week');
for (let i = 0; i < 7; i++) {
week.push(moment(firstDayOfWeek).add(i, 'd'));
};
console.log(week)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
Why it's not giving me the correct total month? (with compared to current mm-yyyy)
function get_total_month(mm,yyyy) {
// custom inputs
var start_date = new Date(yyyy, mm, 01);
// current date
var today_date = new Date();
var today_year = today_date.getFullYear();
var today_month = today_date.getMonth();
var today_day = today_date.getDate();
var end_date = new Date(new Date(today_year, today_month, today_day));
// compare the given date with current date to find the total months
var total_months = (end_date.getFullYear() - start_date.getFullYear())*12 + (end_date.getMonth() - start_date.getMonth());
return total_months;
}
alert(
get_total_month(01, 2014)
);
Giving me: 20 instead of 22
That's because the Date.prototype.getMonth method returns a 0-11 number. So:
January = 0
February = 1
...
December = 11
I think this is what you are looking for, it is another version of your code. But I think is shorter and easier to understand. What do you think?
(I added the +2 to adjust the result to what you are expecting the function to return)
function monthDifference(startDate) {
var months;
var currentDate = new Date();
months = (currentDate.getFullYear() - startDate.getFullYear()) * 12;
months -= startDate.getMonth() + 1;
months += currentDate.getMonth();
return months <= 0 ? 0 : (months + 2);
}
alert(monthDifference(new Date(2014,0)) );
alert(monthDifference(new Date(2013,11)) );
I want to say the number of day with a date.
I have my string; var miadata = 20150925 and I want to say the number of day.
Example:
Domenica = 0;
Lunedi = 1;
Martedi = 2;
Mercoledi = 3;
Giovedi = 4;
Venerdi = 5;
Sabato = 6;
Help me.
Hi you would first have to make a date out of the string:
var miadata = "20150925";
returnDay(miadata);
function returnDay(string){
var yyyy = string.substr(0,4);
var mm = string.substr(4,2);
var dd = string.substr(6,2);
var date = new Date(yyyy+'-'+mm+'-'+dd);
var dayNum = date.getDay();//returns 0-6, where 0-Sunday, 1-Monday and so on..
var days = ["Domenica","Lunedi","Martedi","Mercoledi","Giovedi","Venerdi","Sabato"];
console.log("Day is "+days[dayNum]);
}
You need a base date, something where you know which day it is like: var data=19800106 which is a sunday (Domenica).
From this date you can calculate your actual day:
calculate the difference of days between the two dates (care of the bissextile years every 4 years) and do a modulo on the result:
NbrdayMiaData - NbrDayData = nbrday;
nbrday % 7 = The number you are searching (0, 1, ..., 6).
And then with an array you can easily compare the number to the string.
How do I calculate the age of a user, depending on the date entered in a textbox?
I want to be able to calculate the exact age of YYYY/MM/DD, so far I've only managed to do it by year.
The code I've tried so far:
function OnClick() {
var txtDate = $("#txtDate").val();
var date1 = new Date();
date1.setFullYear(txtDate);
var d1 = date1.getFullYear();
var date2 = new Date();
var d2 = date2.getFullYear();
var age = d2 - d1;
document.getElementById("Diven").innerHTML = age;
}
Any ideas?
When you set the date using this: new Date(birthYear, birthMonth, birthDay); you need to subtract 1 from the month. Months are counted from 00.
For example,
var testDate = new Date(1988,10,12) is Sat Nov 12 1988 00:00:00
You can try this alternate way:
var today = new Date();
var inputBirthDate= new Date(birthYear, birthMonth - 1, birthDay);
var age = today.getFullYear() - inputBirthDate.getFullYear();
var month = today.getMonth() - inputBirthDate.getMonth();
if (month < 0 || (month === 0 && today.getDate() < inputBirthDate.getDate())) {
age--;
}
console.log(age);
This will return you the correct age based on input birth date.
well since i can't make comment, im gonna do it here.
first thing i would do is use momentjs for every date releated thing in js
and if i understand your right, you want something like this?
How to get difference between 2 Dates in Years, Months and days using moment.js
You can use Math.floor and the modulo operator % for integer division:
function CalculateAge() {
var dob1 = $("#txtBirthday").val();
var age1 = document.getElementById("#age");
var dateAry = dob1.value.split("/");
var birthDay = parseInt(dateAry[0]);
var birthMonth = parseInt(dateAry[1]);
var birthYear = parseInt(dateAry[2]);
var birthDate = new Date(birthYear, birthMonth, birthDay);
var currentDate = new Date();
var age = currentDate - birthDate; // don't forget the var keyword
var days = Math.floor(age / 86400000); // no need to use a string
var years = Math.floor(days / 365); // quite inaccurate actually
var remaning_days = days % 365; // use modulo operator
age1.value = years; // no need to type-cast
}
function CalculateAge() {
var dob1 = $("#txtBirthday");
var age1 = $("#age");
var dateAry = dob1.val().split("/");
var birthDay = parseInt(dateAry[0]);
var birthMonth = parseInt(dateAry[1]);
var birthYear = parseInt(dateAry[2]);
var one_day=1000*60*60*24;
var date1 = new Date(birthYear, birthMonth, birthDay);
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2 = new Date();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = date2_ms - date1_ms;
// Convert back to days and return
var t = difference_ms/one_day;
age1.val(t/365);
}
if you want approx year use Math.random in result
The problem that i am having here is that when i minus back to then end of the month, instead of going back to the 29 or 28 of last month the program starts to minus months instead of days. Bellow is my full code and below that is the output it produces in the google spread sheet.
function trying(){
var date = new Date();
var datechange = new Date();
var array = new Array(7);
for (var i = 0; i < 7; i++) {
array[i] = new Array(0);
}
for ( var i = 0; i < 7; i++){
days = i + 8
datechange.setDate(date.getDate() - days);
var tabName = Utilities.formatDate(datechange, 'MST', 'yyyy-MM-dd').toString();
array[i][0] = tabName;
}
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Want");
sheet.getRange("B2:B8").setValues(array);
}
This are the dates that are produced.
05/07/2012
04/07/2012
03/07/2012
02/07/2012
01/07/2012
30/06/2012
30/05/2012
You have to define datechange inside your loop, and not outside:
var date = new Date();
for ( var i = 0; i < 30; i++){
days = i + 8
var datechange = new Date();
datechange.setDate(date.getDate() - i);
console.log(datechange);
}
Date.getDate() returns the date (1-31) - so what you are doing is not correct.
Instead try this:
var ONE_DAY = 24 * 60 * 60 * 1000; //in milliseconds
for ( var i = 0; i < 7; i++){
days = i + 8
datechange.setDate(date.getTime() - (days * ONE_DAY));
var tabName = Utilities.formatDate(datechange, 'MST', 'yyyy-MM-dd').toString();
array[i][0] = tabName;
}
This is how JavaScript dates work. See here for full details.