Convert date string into proper date in Javascript - javascript

I get an array with dates as string from the server, now I want to filter only day, month and year. How can I format the filter result to a certain date format?
var date = ['2015-02-04T23:54:00.000+01:00','2015-02-04T23:54:00.000+01:00', ...];
//wanted result: 2015-02-04 or 04.02.2015

You could convert your what's look to be an ISO Date format like this:
var date = ['2015-02-04T23:54:00.000+01:00','2015-02-04T23:54:00.000+01:00'];
date.map(function(_d) {
var d = new Date(_d)
return d.getFullYear() + '-' + d.getMonth() + 1 + '-' + d.getDay()
}
// if you want to get fancy, you could throw in this function to pad the days and months:
var pad = function (n) {return n<10? '0'+n:''+n;}
var sorted = date.map(function(_d) {
var d = new Date(_d)
return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDay())
})
console.log(sorted);

Date can take an argument of a string. Use a for loop to iterate through your list, and then make a new Date object for each one.
var date = ['2015-02-04T23:54:00.000+01:00','2015-02-04T23:54:00.000+01:00']
var dateObjects = [];
for (var i = 0; i<date.length; i++) {
d = new Date(date[i]);
dateObjects.push(d);
}
Or, in a single line:
var dateObjects = date.map( function (datestr) {return new Date(datestr)} );
Now, you can find the month, day, and year from one of these by the following methods:
var year = dateObjects[0].getFullYear(); // Gets the year
var month = dateObjects[0].getMonth()+1; // Gets the month (add 1 because it's zero-based)
var day = dateObjects[0].getDate(); // Gets the day of the month
dateObjects[0] is just an example that refers to the first date in the list.
So you can then get your output string like
var dateStrings = dateObjects.map(function (item) {
return item.getFullYear()+"-"+(item.getMonth()+1)+"-"+item.getDate();
})

var date = ['2015-02-04T23:54:00.000+01:00','2015-02-04T23:54:00.000+01:00'];
var newdateobject = [];
$.each( date, function(key, e) {
var a = new Date(e);
newdateobject.push(a.getFullYear()+'-'+(a.getMonth()+1) +'-'+a.getDate());
});

IF the format you mentioned is consistent, then:
date.forEach(function(d) {
d = d.substring(0, 10);
})

Related

Expand date range using JS?

I have this variable {{ $daterange }} with json like this
{
"starts_at": "2020-05-20",
"ends_at": "2020-05-23"
},
{
"starts_at": "2020-05-24",
"ends_at": "2020-05-26"
},
{
"starts_at": "2020-05-27",
"ends_at": "2020-05-29"
}
What I want to do is to expand something like this,
2020-05-20
2020-05-21
2020-05-22
2020-05-23
2020-05-24
2020-05-25
2020-05-26
2020-05-27
2020-05-28
2020-05-29
I'm planning to assign these dates inside of expandedDate variable
var expandedDate = [ ....dates ];
This should be done using jquery/js
UPDATE*
Recently this code works and can get all dates between 2 dates. It will list down all dates between 2 date range written in the code.
// Returns an array of dates between the two dates
var getDates = function(startDate, endDate) {
var dates = [],
currentDate = startDate,
addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
while (currentDate <= endDate) {
dates.push(currentDate);
currentDate = addDays.call(currentDate, 1);
}
return dates;
};
// Usage
var dates = getDates(new Date(2013,10,22), new Date(2013,11,25));
dates.forEach(function(date) {
console.log(date);
});
How can I populate {{ $daterange }} contains multiple date range.
Think I missed your update with existing code. The following code seems to get the desired output using javascript. Just added comments to each step as an explanation. Hope it is helpful.
//sample input data
var daterange = [{
"starts_at": "2020-05-27",
"ends_at": "2020-06-23"
},
{
"starts_at": "2020-05-24",
"ends_at": "2020-05-26"
},
{
"starts_at": "2020-05-27",
"ends_at": "2020-05-29"
}
];
// function to get dates between two dates
var getDaysAsArray = function(start_date, end_date) {
for (var arr = [], d = new Date(start_date); d <= end_date; d.setDate(d.getDate() + 1)) {
arr.push(new Date(d));
}
return arr;
};
// function to convert date into the format yyyy-mm-dd
var getFormattedDay = function(date) {
day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
month = date.getMonth()+1 < 10 ? "0" + (date.getMonth()+1) : date.getMonth()+1;
year = date.getFullYear();
return year + "-" + month + "-" + day;
}
//main logic
var expandedDate = [];
//Iterate through the list of arrays in the date range
for (var key in daterange) {
//get first pair of from and to date
var from_string = daterange[key].starts_at;
var to_string = daterange[key].ends_at;
// convert the string date to date format for from and to.
var from_date = new Date(from_string.replace(/(\d{4})-(\d{2})-(\d{2})/, "$1/$2/$3"));
var to_date = new Date(to_string.replace(/(\d{4})-(\d{2})-(\d{2})/, "$1/$2/$3"));
// call getDaysAsArray to convert dates into strings and into an array.
var daylist = getDaysAsArray(from_date, to_date);
// iterate through the daylist and push it into the final array you want to use
for (var day in daylist) {
expandedDate.push(getFormattedDay(daylist[day]));
}
}
// final result required
console.log(expandedDate);
Here's the complete code on how to solve this question
Based on #thommu
var daterange = [
{
"starts_at": "2020-05-24",
"ends_at": "2020-05-26"
},
{
"starts_at": "2020-05-27",
"ends_at": "2020-05-29"
}
];
// function to get dates between two dates
var getDaysAsArray = function(start_date, end_date) {
for (var arr = [], d = new Date(start_date); d <= end_date; d.setDate(d.getDate() + 1)) {
arr.push(new Date(d));
}
return arr;
};
// function to convert date into the format yyyy-mm-dd
var getFormattedDay = function(date) {
day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
month = date.getMonth() < 10 ? "0" + date.getMonth() : date.getMonth();
year = date.getFullYear();
return year + "-" + month + "-" + day;
}
//main logic
var expandedDate = [];
//Iterate through the list of arrays in the date range
for (var key in daterange) {
//get first pair of from and to date
var from_string = daterange[key].starts_at;
var to_string = daterange[key].ends_at;
// convert the string date to date format for from and to.
var xfrom_date = new Date(from_string.replace(/(\d{4})-(\d{2})-(\d{2})/, "$1/$2/$3"));
var xto_date = new Date(to_string.replace(/(\d{4})-(\d{2})-(\d{2})/, "$1/$2/$3"));
//Add +1 month to correct the data
var from_date = new Date(xfrom_date.setMonth(xfrom_date.getMonth()+1));
var to_date = new Date(xto_date.setMonth(xto_date.getMonth()+1));
// call getDaysAsArray to convert dates into strings and into an array.
var daylist = getDaysAsArray(from_date, to_date);
// iterate through the daylist and push it into the final array you want to use
for (var day in daylist) {
expandedDate.push(getFormattedDay(daylist[day]));
}
}
//Filter Duplicated Dates
var dateDuplicate = expandedDate;
var uniqueDate = [];
$.each(dateDuplicate, function(i, el){
if($.inArray(el, uniqueDate) === -1) uniqueDate.push(el);
});
// final result required
console.log(uniqueDate);

How to convert this date into actual date

So this is a new one to me. I've been working with this api and they returned a date in json format that looks like this
{
DateAdd: "/Date(1582936941390-0600)/"
}
not exactly sure how to convert this to a datetime like in the format below so I can actually do something with it.
2020-03-13 23:08:00
i have never seen this date format before! Thanks
Use moment.js to convert the date format
var data = {
DateAdd: "/Date(1582936941390-0600)/"
}
var datam = moment(data.DateAdd)
console.log(datam.format("YYYY-MM-DD HH:mm:ss")) // 2020-02-29 07:42:21
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>
If you don't care about the timezone, you can just cut the timestamp out of that string:
const dateString = data.DateAdd;
const date = new Date(Number(dateString.match(/\d+/)[0]));
You can convert date into desired format by Javascript date object.
let addZero = (i) => {
if (i < 10) {
i = "0" + i;
}
return i;
}
let formatDate = (date) => {
let year = date.getFullYear(),
month = addZero(date.getMonth() + 1),
day = addZero(date.getDate() + 1),
hours = addZero(date.getHours() + 1),
minutes = addZero(date.getMinutes() + 1),
seconds = addZero(date.getSeconds() + 1);
let dateArr = [year, month, day];
let timeArr = [hours, minutes, seconds];
let result = dateArr.join('-').concat(" ", timeArr.join(':'));
return result;
}
let inputString = "/Date(1582936941390-0600)/";
let inputData = new Date(Number(inputString.match(/\d+/)[0]));
console.log(formatDate(inputData));
Please read more about Javascript date object

datetime not returning correct value

Using only JS Write a function that converts user entered date formatted as M/D/YYYY to a format required by an API (YYYYMMDD). The parameter "userDate" and the return value are strings.
For example, it should convert user entered date "12/31/2014" to "20141231" suitable for the API.
I have wrote:
function formatDate(userDate) {
// format from M/D/YYYY to YYYYMMDD
var myDate = new Date(userDate);
var day = myDate.getDay();
var month = myDate.getMonth();
var year = myDate.getFullYear();
var d = day.toString();
var m = month.toString();
var y = year.toString();
return y + m + d;
}
console.log(formatDate("12/31/2014"));
but this is returning: 2014113
should it not return '20141231'
Thanks to #gurvinder372 by +1 I was able to get '20141231'
but the answer is telling me iv passed 0 out of 4...Ive failed on:
Example case: Wrong answer
Two-digit month and day: Wrong answer
One-digit day: Wrong answer
One-digit month: Wrong answer
Months in Date are counted from 0, so this:
myDate.getMonth();
will return 0 for January and so on.
Moreover this:
var day = myDate.getDay();
represents, the day of the week counted from 0, so it should be replaced with this:
var day = myDate.getDate();
For one-digit values, you need to check if it's less than 10 and conditionally prepend it with 0. So the final form of this should be:
function formatDate(userDate) {
// format from M/D/YYYY to YYYYMMDD
var myDate = new Date(userDate);
var day = myDate.getDate();
var month = myDate.getMonth() + 1;
var year = myDate.getFullYear();
var d = +day.toString() < 10 ? '0' + day.toString() : day.toString();
var m = +month.toString() < 10 ? '0' + month.toString() : month.toString();
var y = year.toString(); // no need for check one-digit values
return y + m + d;
}
Hope this helps you
function formatDate(userDate) {
var myDate = new Date(userDate);
var day = myDate.getDate();
var month = myDate.getMonth() + 1; // +1 as month starts with o
var year = myDate.getFullYear();
var d = (day <= 9) ? '0' + day : day.toString(); // append 0 for single digit
var m = (month <= 9) ? '0' + month : month.toString(); // append 0 for single digit
var y = year.toString();
return y + m + d;
}
console.log(formatDate("1/1/2014"));
You can even get rid of using Date constructor. Parsing with date constructor is usually not recommended unless you are using ISO-8601 format as implementation differs in browsers for other formats.
Here is an example with just string split() function.
If you want zero padding for single digit numbers, make use of the pad() function which formats 1 as 01.
function formatDate(userDate) {
// format from M/D/YYYY to YYYYMMDD
var dateArray = userDate.split('/');
var m = +dateArray[0];
var d = +dateArray[1];
var y = +dateArray[2];
var pad = function(n){return n >= 10? n : '0'+n};
// if you want zero padding
// return '' + pad(y) + pad(m) + pad(d);
return '' + y + m + d;
}
console.log(formatDate("12/31/2014"));
but this is returning: 2014113 should it not return '20141231'
Month starts from 0
Replace
var month = myDate.getMonth();
with
var month = myDate.getMonth() + 1;
If you also need to take care of single-digit padding, then do this as well
function padToTwoChar( value )
{
return ( "0" + value ).slice(-2);
}
and your return statement will become
return padToTwoChar( y ) + padToTwoChar( m ) + padToTwoChar( d );

Format Date from String in javascript

I have a string that has a date in it and I wan't to be able to convert it.
var startDate = "March-09-2010";
var convertedStartDate = new Date(startDate);
var month = convertedStartDate.getMonth() + 1
var day = convertedStartDate.getDay();
var year = convertedStartDate.getFullYear();
var shortStartDate = month + "-" + day + "-" + year;
alert(shortStartDate);
I want it so it converts March-09-2010 to 09-03-10 (DD-MM-YY)
Anyone know what I am doing wrong?
var startDate = "March-09-2010";
var convertedStartDate = new Date(startDate.replace(/-/g, "/")); // replace hyphen with slash
var month = convertedStartDate.getMonth() + 1
var date = convertedStartDate.getDate();
var year = convertedStartDate.getFullYear();
var shortStartDate = date + "-" + month + "-" + year;
alert(shortStartDate);
demo: http://jsfiddle.net/BjnBW/
Try this:
var dt=Date.parse(Yourstring);
formatDate('DD-MM-YY',dt);
Please check this Date.parse
Check your syntax changed your code a little, modify it according to it then ---
var startDate = "March/09/2010";
var convertedStartDate = new Date(startDate);
var month = convertedStartDate.getMonth() + 1
var day = convertedStartDate.getDate();
var year = convertedStartDate.getFullYear();
var shortStartDate = day+ "-" + month+ "-" + year;
alert(shortStartDate);
your date string is not in the correct format. for correct formats, please see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
try this or jsfiddle
var startDate = "March-09-2010";
var tmp = startDate.split('-');
tmp.splice(1, 0, ',');
var convertedStartDate = new Date(tmp.join(' '));
var month = convertedStartDate.getMonth() + 1
var day = convertedStartDate.getDate();
var year = convertedStartDate.getFullYear();
var shortStartDate = ('0' + day).slice(-2) + "-" + ('0' + month).slice(-2) + "-" + year;
alert(shortStartDate);
var shortStartDate =
Globalize.format(Globalize.parseDate(startDate, 'MMMM-dd-yyyy'), 'dd-MM-yy');
Use some library to do the conversion, because the built-in Date.parse() is implementation-dependent. It depends on the system locale what formats it accepts.
The code above uses Globalize.js, which can handle a large number of date formats, including formats with month names in different languages (the default being English).
You'll need to convert 'March' to a number. One way is to use this Array extension to be able to retrieve a month number from a month name:
Array.prototype.enum = function(){
var obj = {};
for (var i=0; i<this.length; (i+=1)) {
obj[this[i]] = i;
}
this.enum = obj;
return this;
};
Now, create an Array with month names
var months = ('January,February,March,April,May,June,July,'+
'August,September,October,November,December').split(',')
.enum();
Now you rewrite your date:
var startDate = "March-09-2010".split(/\-/),
month = months.enum[startDate[0]]+1;
startDate = [startDate[1],
month < 10 ? '0'+month : month,
startDate[2]].join('-');
//=> startDate now is: '09-03-2010'
Use getDateFromFormat() to convert string to date in javascript.
Check this link for more help: http://www.mattkruse.com/javascript/date/

JavaScript Date / Time Conversion

I have dates and times in a database in the following format:
2011-08-02T00:00:00-00:00
What is the easiest way to convert them to something like 8-2-2011?
Thanks,
var date = "2011-08-02T00:00:00-00:00".split('T')[0].split('-').reverse();
var month = date[0], day = date[1];
//remove 0 in the beginning if not necessary
if (+month < 10) {
month = month.slice(1);
}
if (+day < 10) {
day = day.slice(1);
}
//swap between the two
date[0] = day;
date[1] = month;
date.join('-');
Or you can use the boring Date way.
Here's the code:
x=new Date("2011-08-02T00:00:00-00:00")
str=(x.getUTCMonth()+1)+"-"+x.getUTCDate()+"-"+x.getUTCFullYear()
Or:
x="2011-08-02T00:00:00-00:00"
x=/^(\d+)\-(\d+)\-(\d+)/.exec(x)
if(x){
str=(parseInt(x[2],10)+"-"+parseInt(x[3],10)+"-"+parseInt(x[1],10))
}
This format will work in the Javascript Date constructor:
var d = new Date("2011-08-02T00:00:00-00:00");
var month = d.getUTCMonth() + 1;
var day = d.getUTCDate();
var year = d.getUTCFullYear();
var output = month + "-" + day + "-" + year;
one way could be to split up the date part
var date = "2011-08-02T00:00:00-00:00";
var dpart = (date.substr(0,10)).split("-");
var odate = parseInt(dpart[1],10)+"-"+parseInt(dpart[2],10)+"-"+dpart[0];

Categories