JS Format 201708 into M yy format - javascript

I have a string in this format 201708 where the first four numbers are the year and the last two the month's. The result being a date of August 2017.
My first idea was to just make it to an date but won't work for me
var formattedDate = new Date("201708")
Thanks for any help

use substring() to split the string into year and month, then use those when calling Date().
let input = '201708';
let year = parseInt(input.substring(0, 4));
let month = parseInt(input.substring(5));
let date = new Date(year, month-1);
console.log(date);
You have to subtract 1 from month because JS counts months starting from 0.

Separate the date with a hyphen.
let b = "201708"
let b_with_hyphen = b.substring(0, 4) + "-" + b.slice(4)
// '2017-08'
let formattedDate = new Date(b_with_hyphen)
console.log(formattedDate.toUTCString())

Related

Javascript how to get full two year from current month?

I have question about getting full two years from the current date. So what i did id get the current month using the new date function and used the for loop to print each of the month. But, i cant really get it to work.... I will post the code that i did below. I would be really appreciate it if anyone can tell me the logic or better way of doing it.
For example: if today current date is august it store into an array from 8 / 2020 9/ 2020 ..... 12/ 2020, 1/2021 and goes to another year to 8/2022.
var d = new Date();
var year = d.getFullYear();
var dateStr;
var currentYear;
var storeMonthYear = [];
for(var i = 1; i <= 24; i++){
dateStr = d.getMonth() + i
currentYear = year;
if(dateStr > "12"){
dateStr = dateStr - 12
// currentYear = year;
// if(currentYear){
// }
storeMonthYear[i] = dateStr + "/" + (currentYear + 1);
}
else if(dateStr > "24"){
storeMonthYear[i] = dateStr + "/" + (currentYear + 1);
}
else{
storeMonthYear[i] = dateStr + "/" + currentYear;
}
storeMonthYear[i] = d.getMonth() + i
}
export const settlementPeriod = [
{
MonthYearFirstRow1: storeMonthYear[1],
MonthYearFirstRow2: storeMonthYear[2],
MonthYearFirstRow3: storeMonthYear[3],
MonthYearFirstRow4: storeMonthYear[4],
MonthYearFirstRow5: storeMonthYear[5],
MonthYearFirstRow6: storeMonthYear[6],
MonthYearFirstRow7: storeMonthYear[7],
MonthYearFirstRow8: storeMonthYear[8],
MonthYearFirstRow9: storeMonthYear[9],
MonthYearFirstRow10: storeMonthYear[10],
MonthYearFirstRow11: storeMonthYear[11],
MonthYearFirstRow12: storeMonthYear[12],
MonthYearSecondRow13: storeMonthYear[13],
MonthYearSecondRow14: storeMonthYear[14],
MonthYearSecondRow15: storeMonthYear[15],
MonthYearSecondRow16: storeMonthYear[16],
MonthYearSecondRow17: storeMonthYear[17],
MonthYearSecondRow18: storeMonthYear[18],
MonthYearSecondRow19: storeMonthYear[19],
MonthYearSecondRow20: storeMonthYear[20],
MonthYearSecondRow21: storeMonthYear[21],
MonthYearSecondRow22: storeMonthYear[22],
MonthYearSecondRow23: storeMonthYear[23],
MonthYearSecondRow24: storeMonthYear[24]
},
];
Create the date from today, get the month and year. Iterate from 0 to 24 for now till in 24 months. If month is 12 than set month to 0 and increment the year. Push the new datestring. Increment the month for the next step.
Note: Beacsue JS counts months form 0-11 you had to add for the datestring 1 for the month and make the change of year at 12 and not 13.
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth();
let res=[];
for (let i=0; i<=24; i++) {
if (month===12) {
month = 0;
year++;
}
res.push(month+1 + '/' + year);
month++;
}
console.log(res);
Here you go, you get an array of strings like "8/2020","9/2020" etc from starting month to the last month including both( in total 25 months).
If you don't want to include last month just delete +1 from for loop condition.
let currentDate = new Date();
let settlementPeriod = [];
let numberOfMonths = 24;
for(let i=0;i<numberOfMonths+1;i++){
settlementPeriod.push(currentDate.getMonth()+1+"/"+currentDate.getFullYear()); //We add current date objects attributes to the array
currentDate = new Date(currentDate.setMonth(currentDate.getMonth()+1)); //Every time we add one month to it
}
console.log(settlementPeriod);
There are a couple of things that stick out in your code sample:
You're comparing strings and numbers (e.g. dateStr > "12"). This will lead to some weird bugs and is one of JS's most easily misused "features". Avoid it where possible.
You increment the year when you reach 12 months from now, rather than when you reach the next January
You're overwriting your strings with this line storeMonthYear[i] = d.getMonth() + i so your array is a bunch of numbers rather than date strings like you expect
Here's a code sample that I think does what you're expecting:
function next24Months() {
const today = new Date()
let year = today.getFullYear()
let monthIndex = today.getMonth()
let dates = []
while (dates.length < 24) {
dates.push(`${monthIndex + 1}/${year}`)
// increment the month, and if we're past December,
// we need to set the year forward and the month back
// to January
if (++monthIndex > 11) {
monthIndex = 0
year++
}
}
return dates
}
In general, when you're dealing with dates, you're probably better off using a library like Moment.js - dates/times are one of the most difficult programming concepts.
While #Ognjen 's answer is correct it's also a bit waseful if your date never escapes its function.
You don't need a new date every time:
function getPeriods(firstMonth, numPers){
var d = new Date(firstMonth.getTime()); // clone the start to leave firstMonth alone
d.setDate(1); // fix after #RobG
var pers = [];
var m;
for(var i = 0; i< numPers; i++){
m = d.getMonth();
pers.push(`${m+ 1}/${d.getFullYear()}`)
d.setMonth(m + 1); // JS dates automatically roll over. You can do this with d.setDate() as well and when you assign 28, 29, 31 or 32 the month and year roll over automatically
}
return pers;
}

Date calculation using javaScript

I need date algorithms, Which will display me how long I have been given a date anywhere.
Example:
Suppose
Today is 01/06/2019 (dd/mm/yy)
BirthDate is 31/05/2019 (dd/mm/yy)
Now, My age is 1 day 0 Months and 0 years
[NOTE: I need all of them, It means day/month and years]
I have been read at least 23 articles/post in this site but they only give years or month or date but not everything in one...
var date, cDate, cMonth, cYears, oDate, oMonth, oYears;
date = new Date()
//current date
cDate = date.getDate()
cMonth = date.getMonth()
cYears = date.getFullYear()
//birth date
oDate = 01
oMonth = 05
oYears = 2019
(Multiplying is not the main solution I think so, need to work with all arithmetics operator)
This will give you the result you need
var birth = new Date("5/31/2019"); // mm/dd/year
var today = new Date();
var diff = today.valueOf()-birth.valueOf();
var result = new Date(diff);
var dayDiff = result.getDate() - 1; //because epoch start from 1st
var yearDiff = result.getFullYear() - 1970; //because epoch start from 1970
var str = `${dayDiff} day ${result.getMonth()} Months and ${yearDiff} years`;
console.log(str);
You should use moment, so there you can do:
var a = moment("04/09/2019 15:00:00");
var b = moment("04/09/2013 14:20:30");
console.log(a.diff(b, 'years'))
console.log(a.diff(b, 'months'))
console.log(a.diff(b, 'days'))
Similarly, you can get minutes, hours and seconds if you need.
While using the library moment.js

Moment.js Duration between Two Dates

How do I get the time difference between two different dates variables, specifically in years, months and days using moment.js?
I found this method but I keep getting weird results. Sometimes the result is one month ahead so I added a subtract one months part to make the result correct, but when the difference between the two dates can be divided into whole years it then becomes a month behind, but then if I remove the subtract month part, it gets even more out of whack.
Also I would like to format it as "X Years, Y Months, Z days", but also can't figure out how to format it in such way.
var dateOne = new Date(2000,07,16);
var dateTwo = new Date (1990,07,16);
var updatedDate = moment(dateOne).format('ll');
var x = moment(dateOne, 'DD/MM/YYYY').diff(moment(dateTwo, 'DD/MM/YYYY'))
var y = moment.duration(x);
var why = moment(x).subtract(1, 'M');
var z = Math.floor(y.asYears()) + moment.utc(why).format('/MM/DD');
console.log(z);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Try this perhaps?
var firstDate = moment();
var secondDate = moment("2018-03-19");
var yearDiff = firstDate.diff(secondDate, "year");
var monthDiff = firstDate.diff(secondDate, "month");
var dayDiff = firstDate.diff(secondDate, "day");
console.log(yearDiff + " Years, " + monthDiff + " Months, " + dayDiff + " Days");
https://jsfiddle.net/px1brLdk/
As stated by others in the comments, you can't format a duration as a date and since dateOne and dateTwo are a Date objects, there is no need for the second argument in moment(dateOne, 'DD/MM/YYYY'), simply use moment(Date).
Moverover, please note that when you use new Date(year, monthIndex, day) monthIndex starts from 0, see MDN docs:
The argument monthIndex is 0-based. This means that January = 0 and December = 11.
You can use moment-duration-format plug-in to format momentjs duration according your needs, see format() docs on the plug-in page.
Here a live sample:
var dateOne = new Date(2000, 7, 16);
var dateTwo = new Date(1990, 7, 16);
var diff = moment(dateOne).diff(moment(dateTwo))
var dur = moment.duration(diff);
var result = dur.format();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/2.2.2/moment-duration-format.min.js"></script>
Moment is having a method called .diff() Use that one.
https://momentjs.com/docs/#/displaying/difference/

Javascript | String date formatting from 4-6-2014 to 2014-06-04

I need to code dates in this format: 4-6-2014
to dates in the following format: 2014-06-04
so i can then construct a date with it.
My approach is:
var date_string = '4-6-2014';
date_string = date_string.substring(6, 10)+'-' + ('0'+date_string.substring(3, 5)).slice(-2) +'-'+ ('0'+(date_string.substring(0, 2))).slice(-2);
var new_date = new Date(date_string);
This code, only works if the string has double-digit days and months, once the string has no leading 0 for days or months it fails..
What would be the solution to this mess...
Regards
Use the simpler (yyyy, mm, dd) constructor:
var date_string = '4-6-2014';
var tmp = date_string.split("-");
var new_date = new Date(tmp[2], +tmp[1] - 1, tmp[0]);
(Swap [0] and [1] is 6 is the day part)

Change date format (Javascript)

I have this code:
var fd=1+self.theDate.getMonth() +'/'+ today+'/'+self.theDate.getFullYear();
It works, but it's format is Month, Day, Year.
I need to change it to: Day, Month Year.
So, I tried this:
var fd=1+today +'/'+ self.theDate.getMonth()+'/'+self.theDate.getFullYear();
Now, my change does not work. Is it that I have not done it properly or is my change right?
Thanks
I expect the correct answer is this:
var fd=today +'/'+ (self.theDate.getMonth() + 1) +'/'+self.theDate.getFullYear();
This leaves today alone, and groups Month so that it does a proper number addition instead of string concatenation.
var theDate = new Date();
var today = theDate.getDate();
var month = theDate.getMonth()+1; // js months are 0 based
var year = theDate.getFullYear();
var fd=today +'/'+ month +'/'+year
or perhaps you prefer 22/05/2011
var theDate = new Date();
var today = theDate.getDate();
if (today<10) today="0"+today;
var month = theDate.getMonth()+1; // js months are 0 based
if (month < 10) month = "0"+month;
var year = theDate.getFullYear();
var fd=""+today +"/"+ month +"/"+year
You are no longer adding 1 to the month, you are adding it to today. Make sure to parenthesize this since "x" + 1 + 2 => "x12" but "x" + (1 + 2) => "x3"

Categories