This question already has answers here:
How to change date format
(2 answers)
Closed 5 years ago.
I've been looking at many similar questions here, but the truth is I haven't been very successful, until I came across an answer that pleases me, but only almost does the trick:
function convertDate (userDate) {
// convert parameter to a date
var returnDate = new Date(userDate);
// get the day, month and year
var y = returnDate.getFullYear();
var m = returnDate.getMonth() + 1;
var d = returnDate.getDay();
// converting the integer values we got above to strings
y = y.toString();
m = m.toString();
d = d.toString();
// making days or months always 2 digits
if (m.length === 1) {
m = '0' + m;
}
if (d.length === 1) {
d = '0' + d;
}
// Combine the 3 strings together
returnDate = y + m + d;
return returnDate;
}
It might be obvious, but the month and day in the output don't work 100% and I just don't know enough to understand why.
Output examples:
convertDate("12/31/2014");
"20141203"
convertDate("02/31/2014");
"20140301"
EDIT:
Replacing getDay for getDate seems to do the trick.
This answer works fine for my case too:
function convertDate (userDate) {
return userDate.substr(6,4) + userDate.substr(3,2) + userDate.substr(0,2);
}
It's because getDay returns a week day 0 to 6. You should use getDate instead.
Your second example is also a wrong date because February never have 31 days.
Perhaps you should try giving [momentjs] a shot. It really facilitate working with dates and transforming between formats using format.
Your code won't work properly even if you replace function getDay for getDate because you are using invalid date format.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#Fall-back_to_implementation-specific_date_formats
Generally if you need to handle only this one date format and it will not be changed in the future than your function can be as simple as:
function convertDate (userDate) {
return userDate.substr(6,4) + userDate.substr(3,2) + userDate.substr(0,2);
}
Change the code var d = returnDate.getDay(); to var d = returnDate.getDate();
function convertDate (userDate) {
// convert parameter to a date
var returnDate = new Date(userDate);
// get the day, month and year
var y = returnDate.getFullYear();
var m = returnDate.getMonth() + 1;
var d = returnDate.getDate();
// converting the integer values we got above to strings
y = y.toString();
m = m.toString();
d = d.toString();
// making days or months always 2 digits
if (m.length === 1) {
m = '0' + m;
}
if (d.length === 1) {
d = '0' + d;
}
// Combine the 3 strings together
returnDate = y + m + d;
return returnDate;
}
Related
So, quick question (searched a lot in Google, but only found the answer which produces same response as below):
code:
var teste = '10/12/2017';
console.log(teste); //returns 10/12/2017
var teste_cut = teste.substr(6,2);
console.log(teste_cut); //returns only 20
What I want is 10/12/17. I can't change how the string is created, so I need to change it after getting said string. Does a method for doing this exist, or should I work around with other functions? I'm feeling stupid right now, since it seens to be a fairly obvious answer, but I guess we all get our stupid moments :P
One method to achieve this would be to cut the start and end portions of the string then join them back together, something like this:
var teste = bookend('10/12/2017', 6, 7);
console.log(teste);
function bookend(str, start, end) {
return str.substr(0, start) + str.substr(end + 1);
}
An alternative would be to use a regular expression to match the parts of the date you want to keep and then join them back together:
var teste = '10/12/2017'.replace(/(\d{2}\/\d{2}\/)(\d{2})(\d{2})/, '$1$3');
console.log(teste);
You can simply rebuild a new string without the parts you don't want using multiple substr :
var test = '10/12/2017';
console.log(test);
var test_cut = test.substr(0,6)+test.substr(8,test.length);
console.log(test_cut)
Simple regular expression with replace. match 4 numbers, keep the last two.
var t = '10/12/2017';
console.log(t.replace(/\d{2}(\d{2})$/, '$1'))
var teste = '10/12/2017'.replace(/(?=....$)../, '');
console.log(teste);
You can use your custom function as -
function formatDate(d)
{
var month = d.getMonth();
var day = d.getDate();
var year = d.getFullYear();
year = year.toString().substr(2,2);
month = month + 1;
month = month + "";
if (month.length == 1)
{
month = "0" + month;
}
day = day + "";
if (day.length == 1)
{
day = "0" + day;
}
return month + "/" + day + "/" + year;
}
var d = new Date('10/12/2017');
console.log(formatDate(d));
Right way would be to deal with Date object instead, it will ensure that you get right year always.
var newDate = new Date(teste);
console.log(((newDate.getFullYear()).toString()).substr(2,2));
This question already has answers here:
Reformat string containing date with Javascript
(3 answers)
Closed 5 years ago.
I need to convert a data from this format 26/03/2017 in this format 2017-03-26, starting from picking data from a form id.
I've tried like this, but I'm lost now.. any help?
var dataform = "26/03/2017";
var dataora = new Date(dataform);
var G = dataora.getDate(dataform);
var M = (dataora.getMonth(dataform) + 1);
if (G < 10)
{
var mm = "0" + dataora.getDate(dataform);
}
else
{
var mm = dataora.getDate(dataform);
}
if (M < 10)
{
var gg = "0" + (dataora.getMonth(dataform) + 1);
}
else
{
var gg = (dataora.getMonth(dataform) + 1);
}
var aa = dataora.getFullYear(dataform);
var data = aa + "-" + mm + "-" + gg;
console.log(data);
console.log("Year "+aa);
console.log("Month "+mm);
console.log("Day "+gg);
Output is:
2019-03-02
Year 2019
Month 03
Day 02
Where am I wrong?
Split the date using split function with /.
Reverse it using the reverse function
Then Join it using the join function with -.
That's it.
var date="26/03/2017";
date=date.split("/").reverse().join("-");
console.log(date);
Where am I wrong?
Don't use the Date constructor (or Date.parse) to parse strings, as it's largely implementation dependent and varies across hosts. See Why does Date.parse give incorrect results?
Per Sagar V's answer, just reformat the string.
Forgive me I tried several searches here and other places in general but cant seem to fix issue I am having at the moment. Can someone please help me figure out?
I am trying to find quarter strings from inputdate in JavaScript. For "01/31/2009" it should give Q1,2013 Q4,2012 etc based on offset given as input parameter. when offset is 0 then current quarter, 1 then previous, 2 then previous 2 quarter etc...
my current code: jsfiddle
function getQuarterStrings(id) {
var d = new Date();
var d = new Date("01/31/2009");
var str;
switch (id) {
...
}
Remaining code is in jsfiddle. As you can see, it fails on second last condition even though everything seems ok. Please help me figure out my mistake. Thank you!
Some of your comparisons are off, and Date tries to compensate for months that don't have as many days when you setMonth. This code should work:
function getQuarterStrings(id) {
var d = new Date("03/31/2009");
d.setDate(1);
d.setMonth(d.getMonth() - id * 3);
var month = d.getMonth() + 1;
var year = d.getFullYear();
var quarter = Math.ceil(month / 3);
return ("Q" + quarter + ", " + year);
}
This works, and is a lot more concise. It also allows you to use any offset instead of a limited set of values:
function getQuarterStrings(date, id) {
// quarter is 0-based here
var quarter = Math.floor(date.getMonth() / 3),
year = date.getFullYear();
quarter -= id;
if(quarter < 0) {
var yearsChanged = Math.ceil(-quarter / 4);
year -= yearsChanged;
// Shift quarter back to a nonnegative number
quarter += 4 * yearsChanged;
}
return "Q" + (quarter + 1) + ", " + year;
}
http://jsfiddle.net/dPmf2/6/
You can also get rid of the switch statement by doing this:
function getQuarterStrings(id) {
var d = new Date();
var d = new Date("01/31/2009");
var str;
if (id !== 0){
d.setMonth(d.getMonth() - 3*id);
}
str = getQuarter(d);
return str;
}
This question already has answers here:
JavaScript function to add X months to a date
(24 answers)
Closed 9 years ago.
I want to add 1 Month or 6 Month to a given Date.
But if i add one Month, the year isnt incremented. And if i add 6 Month to June, i got the Month 00 returned BUT the year is incremented.
Could you please help me out?
function addToBis(monthToAdd){
var tmp = $("#terminbis").val().split('.');
var day = tmp[0];
var month = tmp[1];
var year = tmp[2];
var terminDate = new Date(parseInt(year),parseInt(month), parseInt(day));
terminDate.setMonth(terminDate.getMonth()+monthToAdd);
day = "";
month = "";
year = "";
if(terminDate.getDate() < 10){
day = "0"+terminDate.getDate();
} else{
day = terminDate.getDate();
}
if(terminDate.getMonth() < 10){
month = "0"+terminDate.getMonth();
} else{
month = terminDate.getMonth();
}
year = terminDate.getFullYear();
$("#terminbis").val(day+"."+month+"."+year);
}
getMonth returns a number from 0 to 11 which means 0 for January , 1 for february ...etc
so modify like this
var terminDate = new Date(parseInt(year),parseInt(month - 1), parseInt(day));
terminDate.setMonth(terminDate.getMonth()+monthToAdd);
and
month = terminDate.getMonth() + 1;
You should use the javascript Date object's native methods to update it. Check out this question's accepted answer for example, it is the correct approach to your problem.
Javascript function to add X months to a date
The function can be written much more concisely as:
function addToBis(monthToAdd){
function z(n) {return (n<10? '0':'') + n}
var tmp = $("#terminbis").val().split('.');
var d = new Date(tmp[2], --tmp[1], tmp[0]);
d.setMonth(d.getMonth() + monthToAdd);
$("#terminbis").val(z(d.getDate()) + '.' + z(d.getMonth() + 1)
+ '.' + d.getFullYear();
}
The value of terminbis and monthToAdd should be validated before use, as should the date generated from the value.
Okay, so using the following function:
function date_add(date, days)
{
var dim = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31};
console.log(date.split("/"));
var date_arr = date.split("/");
console.log(date_arr);
...
}
I get the following output at the console screen for date_add("12/08/1990", 1)
["12", "08", "1990"]
["2", "08", "1990"]
Spending an hour struggling with what could fix this weird problem, on a whim I changed my function to the following:
function date_add(date, days)
{
var dim = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31};
date = date.split("/");
console.log(date);
...
}
Magically, the code works again. Now don't get me wrong, I'm ecstatic that it worked. I'm seriously concerned over why it worked, though, when the other didn't. More or less I'm just concerned with why the other didn't work. Does anyone have a good explanation?
Edit: Now they're both broken. >.>
For Tomas, here is the full function:
function date_add(date, days)
{
var dim = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31};
console.log(date);
console.log(date.split("/"));
date_arr = date.split("/");
console.log(date)
if (date_arr[0][0] = "0") date_arr[0] = date_arr[0][1];
if (date_arr[1][0] = "0") date_arr[1] = date_arr[1][1];
var month = parseInt(date_arr[0]);
var day = parseInt(date_arr[1]);
var year = parseInt(date_arr[2]);
console.log(month);
console.log(day);
console.log(year);
if ((year%4 == 0 && year%100 != 0) || year%400 == 0)
dim[2] = 29;
day += days;
while (day < 1)
{
month--;
if (month < 1)
{
month = 12;
year--;
}
day += dim[month];
}
while (dim[month] < day)
{
day -= (dim[month]+1);
month++;
if (month > 12)
{
month = 0;
year++;
}
}
return ""+month+"/"+day+"/"+year;
}
As for the input for the function, I called this function from the console using date_add('12/08/1990',1);
The problem with your original code is most probably you were not using the second parameter for your parseInt() calls, which is to specify the base for which you want to convert to, by default it assumes a 10 base, but when the number starts with zero as in your 08 case, then it assumes its an octal number, so the solution is to use the second parameter in your parseInt calls, like this:
var month = parseInt(date_arr[0], 10);
var day = parseInt(date_arr[1], 10);
var year = parseInt(date_arr[2], 10);
This behaviour have been fixed in last versions of javascript (EcmaScript 5), see this question for more info:
How do I work around JavaScript's parseInt octal behavior?