Convert date in JavaScript [duplicate] - javascript

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.

Related

Remove part of string but getting the deleted part as result

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));

Convert MM/DD/YYYY to the format YYYYMMDD (javascript) [duplicate]

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;
}

Insert character in string using javascript [duplicate]

This question already has answers here:
Insert a string at a specific index
(19 answers)
Closed 6 years ago.
I have this date1, I want to insert "-" to make it 2016-09-23. Is anyone know how to do this using javascript?
var date1 = "20160923";
You can use regex:
var ret = "20160923".replace(/(\d{4})(\d{2})(\d{2})/, "$1-$2-$3");
console.log(ret);
/)
Given that the year is 4 digit and month and day are 2 digit you can use this code
var date1 = "20160923";
var formattedDate = date1.slice(0, 4) + "-" + date1.slice(4, 6) + "-" + date1.slice(6, 8);
console.log(formattedDate);
There is no direct method for this, you can write your own Method like InsertAt(char,pos) using Prototype object [References from here]
String.prototype.InsertAt=function(CharToInsert,Position){
return this.slice(0,Position) + CharToInsert + this.slice(Position)
}
Then use it like this
"20160923".InsertAt('-',4); //Output :"2016-0923"
Assuming date1 is always consistent...
var date2 = date1.slice(0, 4) + '-' + date1.slice(4, 6) + '-' + date1.slice(6, 8);

jQuery: Add 4 weeks to date in format dd-mm-yyyy

I have a string which has a date in the format: dd-mm-yyyy
How I can add 4 weeks to the string and then generate a new string using jQuery / Javascript?
I have
var d = new Date(current_date);
d.setMonth(d.getMonth() + 1);
current_date_new = (d.getMonth() + 1 ) + '-' + d.getDate() + '-' + d.getFullYear();
alert(current_date_new);
but it complains that the string provided is in the incorrect format
EDIT: After a bit of fiddling, here's the solution:
First, split the string to individual parts.
var inputString = "12-2-2005";
var dString = inputString.split('-');
Then, parse the string to a datetime object and add 28 days (4 weeks) to it.
var dt = new Date(dString[2],dString[1]-1,dString[0]);
dt.setDate(dt.getDate()+28);
Finally, you can output the date
var finalDate = dt.GetDate() + "-" + (dt.GetMonth()+1) + "-" + dt.GetYear();
This code should return 12-3-2005.
CAVEATS: It seems JavaScript's Date object takes 0-11 as the month field, hence the -1 and +1 to the month in the code.
EDIT2: To do padding, use this function:
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
and change your output to
var finalDate = pad(dt.GetDate(),2) + "-" + pad(dt.GetMonth()+1,2) + "-" + dt.GetYear();
Check the updated fiddle.
There is no need to convert to mm-dd-yyyy, simple split string by the minus sign and create new Date object with the following code:
var string = '12-02-2012';
var split = string.split('-');
var date = Date(split[2],parseInt(split[1])-1,parseInt(split[0])+1)
date.setDate(date.getDate() + 28);
var fourWeeksLater = date.getDay() + "-"+date.getMonth() +"-"+date.getYear();
This should be working:
var formattedDate = '01-01-2012',
dateTokens = formattedDate.split('-'),
dt = new Date(dateTokens[2], parseInt( dateTokens[1], 10 ) - 1, dateTokens[0]), // months are 0 based, so need to add 1
inFourWeeks = new Date( dt.getTime() + 28 * 24 * 60 * 60 * 1000 );
jsfiddle: http://jsfiddle.net/uKDJP/
Edit:
Using Globalize you can format inFourWeeks:
Globalize.format( inFourWeeks, 'dd-MM-yyyy' ) // outputs 29-01-2012
Instead of writing your own parser for dates, I would use moment.js.
To parse your date:
var date = moment('14-06-2012', 'DD-MM-YYYY');
To add 4 weeks to it:
date.add('weeks', 4);
Or in one go:
var date = moment('14-06-2012', 'DD-MM-YYYY').add('weeks', 4);
And convert it to string:
var dateString = date.format('DD-MM-YYYY');

Convert datetime to valid JavaScript date [duplicate]

This question already has answers here:
Convert date from string in javascript
(4 answers)
Closed 3 years ago.
I have a datetime string being provided to me in the following format:
yyyy-MM-dd HH:mm:ss
2011-07-14 11:23:00
When attempting to parse it into a JavaScript date() object it fails. What is the best way to convert this into a format that JavaScript can understand?
The answers below suggest something like
var myDate = new Date('2011-07-14 11:23:00');
Which is what I was using. It appears this may be a browser issue. I've made a http://jsfiddle.net/czeBu/ for this. It works OK for me in Chrome. In Firefox 5.0.1 on OS X it returns Invalid Date.
This works everywhere including Safari 5 and Firefox 5 on OS X.
UPDATE: Fx Quantum (54) has no need for the replace, but Safari 11 is still not happy unless you convert as below
var date_test = new Date("2011-07-14 11:23:00".replace(/-/g,"/"));
console.log(date_test);
FIDDLE
One can use the getmonth and getday methods to get only the date.
Here I attach my solution:
var fullDate = new Date(); console.log(fullDate);
var twoDigitMonth = fullDate.getMonth() + "";
if (twoDigitMonth.length == 1)
twoDigitMonth = "0" + twoDigitMonth;
var twoDigitDate = fullDate.getDate() + "";
if (twoDigitDate.length == 1)
twoDigitDate = "0" + twoDigitDate;
var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear(); console.log(currentDate);
Just use Date.parse() which returns a Number, then use new Date() to parse it:
var thedate = new Date(Date.parse("2011-07-14 11:23:00"));
Use:
enter code var moment = require('moment')
var startDate = moment('2013-5-11 8:73:18', 'YYYY-M-DD HH:mm:ss')
Moment.js works very well. You can read more about it here.
function ConvertDateFromDiv(divTimeStr) {
//eg:-divTimeStr=18/03/2013 12:53:00
var tmstr = divTimeStr.toString().split(' '); //'21-01-2013 PM 3:20:24'
var dt = tmstr[0].split('/');
var str = dt[2] + "/" + dt[1] + "/" + dt[0] + " " + tmstr[1]; //+ " " + tmstr[1]//'2013/01/20 3:20:24 pm'
var time = new Date(str);
if (time == "Invalid Date") {
time = new Date(divTimeStr);
}
return time;
}
You can use moment.js for that, it will convert DateTime object into valid Javascript formated date:
moment(DateOfBirth).format('DD-MMM-YYYY'); // put format as you want
Output: 28-Apr-1993
Hope it will help you :)
new Date("2011-07-14 11:23:00"); works fine for me.
You can use get methods:
var fullDate = new Date();
console.log(fullDate);
var twoDigitMonth = fullDate.getMonth() + "";
if (twoDigitMonth.length == 1)
twoDigitMonth = "0" + twoDigitMonth;
var twoDigitDate = fullDate.getDate() + "";
if (twoDigitDate.length == 1)
twoDigitDate = "0" + twoDigitDate;
var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear(); console.log(currentDate);

Categories

Resources