How can I convert string to datetime with format specification in JavaScript?
I think this can help you: http://www.mattkruse.com/javascript/date/
There's a getDateFromFormat()
function that you can tweak a little to solve your problem.
Update: there's an updated version of the samples available at javascripttoolbox.com
Convert string to datetime
For this format (assuming datepart has the format dd-mm-yyyy) in plain javascript use dateString2Date
. It may bite you, because of browser compatibility problems.
tryParseDateFromString
is ES6 utility method to parse a date string using a format string parameter (format
) to inform the method about the position of date/month/year in the input string. The date is constructed using Date.UTC
, circumventing the aforementioned browser compatibility problems.
See also
// fixed format dd-mm-yyyy
function dateString2Date(dateString) {
const dt = dateString.split(/\-|\s/);
return new Date(dt.slice(0, 3).reverse().join('-') + ' ' + dt[3]);
}
// multiple formats (e.g. yyyy/mm/dd (ymd) or mm-dd-yyyy (mdy) etc.)
function tryParseDateFromString(dateStringCandidateValue, format = "ymd") {
const candidate = (dateStringCandidateValue || ``)
.split(/[ :\-\/]/g).map(Number).filter(v => !isNaN(v));
const toDate = () => {
format = [...format].reduce((acc, val, i) => ({ ...acc, [val]: i }), {});
const parts =
[candidate[format.y], candidate[format.m] - 1, candidate[format.d] ]
.concat(candidate.length > 3 ? candidate.slice(3) : []);
const checkDate = d => d.getDate &&
![d.getFullYear(), d.getMonth(), d.getDate()]
.find( (v, i) => v !== parts[i] ) && d || undefined;
return checkDate( new Date(Date.UTC(...parts)) );
};
return candidate.length < 3 ? undefined : toDate();
}
const result = document.querySelector('#result');
result.textContent =
`*Fixed\ndateString2Date('01-01-2016 00:03:44'):\n => ${
dateString2Date('01-01-2016 00:03:44')}`;
result.textContent +=
`\n\n*With formatting dmy
tryParseDateFromString('01-12-2016 00:03:44', 'dmy'):\n => ${
tryParseDateFromString('01-12-2016 00:03:44', "dmy").toUTCString()}`;
result.textContent +=
`\n\n*With formatting mdy
tryParseDateFromString('03/01/1943', 'mdy'):\n => ${
tryParseDateFromString('03/01/1943', "mdy").toUTCString()}`;
result.textContent +=
`\n\n*With invalid format
tryParseDateFromString('12-13-2016 00:03:44', 'dmy'):\n => ${
tryParseDateFromString('12-13-2016 00:03:44', "dmy")}`;
result.textContent +=
`\n\n*With formatting invalid string
tryParseDateFromString('03/01/null', 'mdy'):\n => ${
tryParseDateFromString('03/01/null', "mdy")}`;
result.textContent +=
`\n\n*With formatting no parameters
tryParseDateFromString():\n => ${tryParseDateFromString()}`;
<pre id="result"></pre>
Convert string to a DateTime format without converting it to your Local Time
Try use with Regex
pattern /-|:|T/g
for split()
var t = "2017-05-01T07:40:00.000+10:00";
var s =t.split(/-|:|T/g).slice(0,5)
var c =parseInt(s[3]) > 12 ? parseInt(s[3])-12 : s[3];
var f =parseInt(s[3]) > 12 ? 'PM' : 'AM';
console.log(s[1]+'/'+s[2]+'/'+s[0]+' '+c+':'+s[4]+' '+f);
How to convert date into specific date format
Using toLocaleDateString
options
let date = new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit' })
console.log(date)
Converting Javascript String to Datetime
Looks like Date.parse
is not going to work because the format the datepicker is returning.
You might want to look at the following thread for parsing solutions or change your format that the datepicker outputs to one of the supported formats.
How can I convert string to datetime with format specification in JavaScript?
http://blog.dygraphs.com/2012/03/javascript-and-dates-what-mess.html
Useful parse info:
http://msdn.microsoft.com/en-us/library/ie/ff743760(v=vs.94).aspx
Related Topics
No Visible Cause For "Unexpected Token Illegal"
Check If an Array Contains Any Element of Another Array in JavaScript
Angularjs Routing Without the Hash '#'
Programmatically Changing Webkit-Transformation Values in Animation Rules
Changing Background Based on Time of Day (Using JavaScript)
Repeat Animation Every 3 Seconds
Call Java Function from JavaScript Over Android Webview
Create an Array of Characters from Specified Range
Vuejs: Why Is "This" Undefined
Es6 Class Variable Alternatives
Take a Screenshot of a Webpage With JavaScript
Changing the Image Source Using Jquery
Are JavaScript Strings Immutable? Do I Need a "String Builder" in JavaScript
Fastest Method to Replace All Instances of a Character in a String
Is It Not Possible to Stringify an Error Using Json.Stringify