This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Closed 3 years ago.
I want to parse dates (string date format to javascript date format), but I have various string date format like YYYY-MM-DD, DD-MM-YYYY and 'DD/MM/YYYY' and so..
Is there any generic procedure or way to convent from these string date format to javascript date format?
These are two libraries that I use for that:
moment.js
datejs
Here userFormat string could be in these format 'DD-MM-YYYY', 'YYYY-MM-DD', 'DD/MM/YYYY' etc..
function parseDate(dateString, userFormat) {
var delimiter, theFormat, theDate, month, date, year;
// Set default format if userFormat is not provided
userFormat = userFormat || 'yyyy-mm-dd';
// Find custom delimiter by excluding
// month, day and year characters
delimiter = /[^dmy]/.exec(userFormat)[0];
// Create an array with month, day and year
// so we know the format order by index
theFormat = userFormat.split(delimiter);
//Create an array of dateString.
theDate = dateString.split(delimiter);
for (var i = 0, len = theDate.length; i < len; i++){
//assigning values for date, month and year based on theFormat array.
if (/d/.test(theFormat[i])){
date = theDate[i];
}
else if (/m/.test(theFormat[i])){
month = parseInt(theDate[i], 10) - 1;
}
else if (/y/.test(theFormat[i])){
year = theDate[i];
}
}
return (new Date(year, month, date));
}
Just go get datejs.
http://www.datejs.com/
...and never bother with writing your own Javascript date functions again.
function dateParsing(toDate, dateFormat) {
var dt = Date.parseInvariant(todate, dateFormat); // pass date and your desired format e.g yyyy/M/dd
alert(dt); // to check date
}
Related
This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 10 months ago.
I'm trying to create a date with the format 'mmddyyyy'. I've noticed I can pass a four digit string, but when I use the format above, it says invalid date. How can I go about this with pure js?
let dateString = '01012022'
let d = new Date(dateString)
maybe you want something like that
let dateString = '01012022'
let [match, dd, mm, yyyy] = dateString.match(/(\d{2})(\d{2})(\d{4})/)
// iso format
let d = new Date(`${yyyy}${mm}${dd}`)
Seems like you have to split your string into pieces then use common Date() constructor with separated day, month and year
//Your string with date
let dateString = '01012022';
//extracting 2 first numbers as m (month), 2 second as d (day) and the last 4 as y (year)
let {d,m,y} = /(?<m>\d{2})(?<d>\d{2})(?<y>\d{4})/.exec(dateString).groups;
//then create new date using constructor
let date = new Date(y,m,d);
This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
I'm trying to convert a date in string format to a Date object in JavaScript. The date is coming from the openweathermap.org API, which gives the date string in the following format:
'2018-04-28 09:00:00' or 'yyyy-mm-dd hh:mm:ss'
I know that the JavaScript Date class can take other string formats of dates, but this one returns NaN when I try anything with it. How can I convert a date string, like the one above, and convert it easily to a JavaScript object? Thanks!
Since you are getting NaN while directly converting the string to date. You can split the string on spaces, - and : and then pass the value to date constructor and generate the date object.
const str = `2018-04-28 09:00:00`;
const [date, time] = str.split(' ');
const [year, month, day] = date.split('-');
const [hh, mm, sec] = time.split(':');
const dateObj = new Date(year, month - 1, day, hh, mm, sec);
console.log(dateObj);
As pointed out by #RobG, this could also be done using the regex.
const str = `2018-04-28 09:00:00`;
var b = str.split(/\D/);
var date = new Date(b[0],b[1]-1,b[2],b[3],b[4],b[5]);
console.log(date);
const str = `2018-04-28 09:00:00`,
date = new Date(...(str.split(/\D/).map((v,i)=>i==1?--v:v)));
console.log(date);
Just try new Date(str)
d = new Date("2018-04-20 09:00:00")
Fri Apr 20 2018 09:00:00 GMT+0800 (Hong Kong Standard Time)
d.getDate()
20
ref: https://www.ecma-international.org/ecma-262/6.0/#sec-date-time-string-format
This question already has answers here:
How can I convert string to datetime with format specification in JavaScript?
(15 answers)
How to parse a string into a date object at JavaScript?
(2 answers)
Closed 5 years ago.
my function returns the selected date of a calendar in this format:
var returnValue = "6.7.2017"; //day.month.year
When i try to use it for a new Date, it does not work:
var weekdays = ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'];
var wkdayname = new Date(returnValue); //Error: returnValue ist NaN
var dayName = weekdays[wkdayname.getDay()];
All I want is just the name of the weekday of this date.
Do you have any suggestions ?
The date format also has the day and month switched from the format that Date() recognizes. This function transforms a date string using . and day first notation to the valid format:
function transformDate (date){
var day_month_year = date.split(".")
return [day_month_year[1],day_month_year[0],day_month_year[2]].join("/")
}
var returnValue = "6.7.2017"; //This is a string
var weekdays = ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'];
var wkdayname = new Date(transformDate(returnValue));
var dayName = weekdays[wkdayname.getDay()];
alert(dayName)
You can validate a date string using the Date.parse() API.
But mind you, this API's validation is a bit loose as it accepts both ISO 8601 or RFC 2822 date formats. If it is a valid date then the API returns you the epoch time which can then be used for creating the Javascript Date object. Otherwise it returns NaN.
As for getting the day - you can use the .getDay() API.
Example:
if (Date.parse("aaabbcc")) {
console.log("aaabbcc is Valid");
}
else {
console.log("aaabbcc is invalid");
}
if (Date.parse("6.7.2017")) {
var date = new Date(Date.parse("6.7.2017"));
console.log("6.7.2017 is Valid");
console.log("The day of the week is => " + date.getDay());
}
else {
console.log("6.7.2017 is invalid");
}
References:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
I have unfortunetly a nonstandard date
Jul-23-2017
Is there any way to convert it to a unix timestamp in javascript?
new Date("Jul-23-2017").getTime();
To make sure you pass valid values to the date contructor, you can parse the date yourself
var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var date = "Jul-23-2017";
var parts = date.split('-');
var unix = (new Date(parts[2], months.indexOf(parts[0]), parts[1])).getTime();
console.log(unix)
I'm new to moment.js and I can't really understand the documentation. I'd like to manipulate some dates in string format.
I have my date as string from json feed and looks like:
var year = item.date
// it returns a string like "25/04/2012"
How do I extract the year from it using moment.js ?
You can use
moment("25/04/2012","DD/MM/YYYY").format("YYYY")
or
moment("25/04/2012","DD/MM/YYYY").year()
in your example:
moment(item.date,"DD/MM/YYYY").year()
Or you can convert the string to date then extract the year:
var date = new Date(dateString);
if (!isNaN(date)) {
return date.getFullYear();
}