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.
Related
This question already has answers here:
Difference between two dates in years, months, days in JavaScript
(34 answers)
How to get difference between 2 Dates in Years, Months and days using moment.js
(3 answers)
How to get the difference of two dates in mm-dd-hh format in Javascript
(3 answers)
Closed 2 years ago.
I am trying to get the difference between two dates (my birthday and the current date to get the time left until my birthday), But I want the output format in ('Year/Months/Days); How can I do that? that's what I've tried so far :
const birthday = new Date ('11-20-2021').getTime();
const today = new Date ().getTime();
const dys = (1000*60*60*24);
const months = (dys*30);
let differance = birthday-today ;
const formatted = Math.round(differance/dys);
console.log(formatted);`
thank you in advance
How do you feel about the modulo operator? :)
This is a common math operation, like finding change or such. Think of it this way, if you have a large number of days, say 397, you can get number of years by doing integer division (1), then you can get the number of days left by doing modulo by a year to get the remainder (in days) 397%365 = 32. Then you can repeat the process to get number of months remaining (1...assuming 30 day month) in that and again, modulo to get the final number of days 2 ...
I'm no javascript pro, but I think you need to use Math.floor(quotient) to get the result of division in integer format.
this example compares between the current date and the date 2100/0/14 try the same concept in the example and i hope it helps:
var today, someday, text;
today = new Date();
someday = new Date();
someday.setFullYear(2100, 0, 14);
if (someday > today) {
text = "Today is before January 14, 2100.";
} else {
text = "Today is after January 14, 2100.";
}
document.getElementById("demo").innerHTML = text;
Working with dates and differences can be difficult because there are a lot of edge cases. which is why I prefer to let a dedicated library handle this, like https://momentjs.com/
moment has a plugin (https://www.npmjs.com/package/moment-precise-range-plugin) which does exactly what you are looking for:
import moment from 'moment';
import 'moment-precise-range-plugin';
var m1 = moment('2014-01-01 12:00:00','YYYY-MM-DD HH:mm:ss');
var m2 = moment('2014-02-03 15:04:05','YYYY-MM-DD HH:mm:ss');
var diff = moment.preciseDiff(m1, m2, true); // {years : 0, months : 1, days : 2, hours : 3, minutes : 4, seconds : 5}
var str = `Years: ${diff.years}, Months: ${diff.months}, Days: ${diff.days} `; // 'Years: 0, Months: 1, Days: 2'
If I got you right, I've done it this way.
Haven't touched your original code, but added a function that calculates the dateTime output of the total days of difference.
const birthday = new Date('11-20-2021').getTime();
const today = new Date().getTime();
const dys = (1000 * 60 * 60 * 24);
const months = (dys * 30);
let totalDayserance = birthday - today;
const formatted = daysToDateTime(totalDayserance / dys);
console.log(formatted);
function daysToDateTime(totalDays) {
var baseVal = '';
var formedValues = [
['Years', 365],
['Months', 30],
['Days', 1]
];
for (var i = 0; i < formedValues.length; i++) {
var valueByGroup = Math.floor(totalDays / formedValues[i][1]); //by months
if (valueByGroup >= 1) {
baseVal += (valueByGroup + formedValues[i][0]) + ', ';
totalDays -= valueByGroup * formedValues[i][1];
}
}
return baseVal;
}
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());
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 will explain my question in the code itself. Please see the below code
var monthNames = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
var ctdate = (new Date()).getMonth() + 1;// getting current month
var str=new Date().getFullYear()+'';
str= str.match(/\d{2}$/);//current year is 15(as this year is 2015)
var strprev= str-1;//previous year is 14
var dynmonths = new Array();
dynmonths = monthNames.slice(ctdate).concat(monthNames.slice(0, ctdate));
//here the output comes for last 12 months starting from currentmonth-12 (i.e APR in this case) to current month (i.e MAR)
//dynmonths = ["APR","MAY","JUN","JUL","AUG","SEP","AUG","SEP","OCT","NOV","DEC","JAN","FEB","MAR"];
//I am rotating dynmonths in a for loop to get full dates i.e between (01-APR-14 to 01-MAR-15)
for (var i = 0, length = dynmonths.length; i < length; i++) {
var month = '01-' + dynmonths[i] + '-' + strcurrent;
}
But the problem is that month is taking 14for all the months. Which is wrong. After 01-DEC-14 the next month must be 01-JAN-15, 01-FEB-15 and so on. How to check DEC in for loop and after DEC year must change to year+1
Thanks in advance
use below code it will work.
function ddd()
{
var monthNames = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
var ctdate = (new Date()).getMonth() + 1;// getting current month
var str=new Date().getFullYear()+'';
str= str.match(/\d{2}$/);//current year is 15(as this year is 2015)
var strprev= str-1;//previous year is 14
var dynmonths = new Array();
dynmonths = monthNames.slice(ctdate).concat(monthNames.slice(0, ctdate));
//here the output comes for last 12 months starting from currentmonth-12 (i.e APR in this case) to current month (i.e MAR)
//dynmonths = ["APR","MAY","JUN","JUL","AUG","SEP","AUG","SEP","OCT","NOV","DEC","JAN","FEB","MAR"];
//I am rotating dynmonths in a for loop to get full dates i.e between (01-APR-14 to 01-MAR-15)
for (var i = 0, length = dynmonths.length; i < length; i++) {
if(dynmonths[i]=='JAN')
{
var str = parseInt(str)+parseInt(1);
}
var month = '01-' + dynmonths[i] + '-' + str;
document.writeln(month);
document.write("<br />");
}
}
<body onload="ddd()">
You can declare variable bool = false and check if you on DEC change it to true (or use counter from more then one year):
var monthNames = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
var ctdate = (new Date()).getMonth() + 1;// getting current month
var str=new Date().getFullYear()+'';
str= str.match(/\d{2}$/);//current year is 15(as this year is 2015)
var strprev= str-1;//previous year is 14
var dynmonths = new Array();
dynmonths = monthNames.slice(ctdate).concat(monthNames.slice(0, ctdate));
//here the output comes for last 12 months starting from currentmonth-12 (i.e APR in this case) to current month (i.e MAR)
//dynmonths = ["APR","MAY","JUN","JUL","AUG","SEP","AUG","SEP","OCT","NOV","DEC","JAN","FEB","MAR"];
//I am rotating dynmonths in a for loop to get full dates i.e between (01-APR-14 to 01-MAR-15)
var isPassYear = false;
for (var i = 0, length = dynmonths.length; i < length; i++) {
var month;
if (isPassYear)
//do something
else
month = '01-' + dynmonths[i] + '-' + strcurrent;
if (monthNames[11] == dynmonths[i]) {
isPassYear = true;
}
}
second option is to use Date object and append his month by one each time, if you set append to month number 12 it automatic go to the next year.
I have for example two dates:
var first = '2013-07-30';
var second = '2013-08-04';
How can i show all dates between first and second?
This should return me:
2013-07-30
2013-07-31
2013-08-01
2013-08-02
2013-08-03
2013-08-04
In PHP I can get dates to strtotime and use a while loop. But how can I do it in jQuery?
I would like have this in array.
var day = 1000*60*60*24;
date1 = new Date('2013-07-30');
date2 = new Date("2013-08-04");
var diff = (date2.getTime()- date1.getTime())/day;
for(var i=0;i<=diff; i++)
{
var xx = date1.getTime()+day*i;
var yy = new Date(xx);
console.log(yy.getFullYear()+"-"+(yy.getMonth()+1)+"-"+yy.getDate());
}