This question already has answers here:
javascript: how to parse a date string
(4 answers)
Closed 5 years ago.
In javascript, while using exif-js to extract metadata of an image file, I am getting date time format as 2017:03:09 14:49:21.
The value in the DateTimeOriginal property is formatted as YYYY:MMY:DD HH:MM:SS. When I use var d = new Date(2017:03:09 14:49:21), it returns NaN. It's the colons in between the YYYY, MM, and DD which causes problem.
How to solve this problem?
Thanks in advance.
Don't use the built-in parser (i.e. Date constructor or Date.parse) for parsing strings as it's largely implementation dependent and unreliable. If you can trust the date to be valid, then the following will do:
/* Parse date string in YYYY-MM-DD hh:mm:ss format
** separator can be any non-digit character
** e.g. 2017:03:09 14:49:21
*/
function parseDate(s) {
var b = s.split(/\D/);
return new Date(b[0],b[1]-1,b[2],b[3],b[4],b[5]);
}
console.log(parseDate('2017:03:09 14:49:21').toString());
It's fairly easy to add validation to the values. Otherwise, use a library and make sure you specify the format to parse.
My recommendation would be to use Moment (http://momentjs.com/docs/), as it provides clean parsing of dates. With Moment, what you want is this:
var tstamp = moment("2017:03:09 14:49:21", "YYYY:MM:DD HH:mm:ss");
var date = tstamp.toDate();
You can do simple string manipulation and create date if the format is always the same, as:
var str = "2017:03:09 14:49:21".split(" ");
//get date part and replace ':' with '-'
var dateStr = str[0].replace(/:/g, "-");
//concat the strings (date and time part)
var properDateStr = dateStr + " " + str[1];
//pass to Date
var date = new Date(properDateStr);
console.log(date);
Related
This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Closed 5 months ago.
When working with the task, it became necessary to get dates from html, and to find out the time difference between them:
var now_time_div = document.getElementById("time_now_of");
var start_time_div = document.getElementById("time_when_start_of");
var time_now = now_time_div.textContent || now_time_div.innerHTML;
var time_start = start_time_div.textContent || start_time_div.innerHTML;
After that, without thinking about the format of the data, I wanted to find the time difference in ms:
var worked_time = time_now - time_start
That didn't work, because we are working with a string.
After entering the directory, I found the Date.parse() function, which returns the amount of time that has passed since the given date:
var worked_time = Date.parse(time_start);
but it turned out that it works only with a correctly submitted strig, for example
We need to have:
Date.parse('01 Jan 1970 00:00:00 GMT');
We have:
Date.parse('21.09.2022, 15:34:21')
Maybe someone knows an easy way to implement this without rebuilding the string?
If you don't want to bring in a library like moment.js, you can just massage the date string a bit so it can be parsed correctly
const dateString = '21.09.2022, 15:34:21';
const curDate = dateString.split(',')[0].substring(0, 10).split('.');
const curTime = dateString.split(',')[1];
const parsed = `${curDate[1]}'/'${curDate[0]}'/'${curDate[2]} ${curTime}`;
console.log(new Date(parsed).toString()); // Properly formatted date
You can used this parsed variable to compare to other properly formatted dates
You can use moment.js to parse custom date formats just as in for example Java:
https://momentjs.com/docs/#/parsing/string-format/
After that you can simply convert it to a js date using the toDate function: https://momentjs.com/docs/#/displaying/as-javascript-date/
Edit Example:
var mDate = moment('2022-09-21 10:15:00', 'YYYY-MM-DD HH:mm:ss');
var jsDate = mDate.toDate();
This question already has answers here:
Format JavaScript date as yyyy-mm-dd
(50 answers)
Closed 2 years ago.
I have date string in the format '2020/02/25 23:58:08' . I want to parse it to '2020-02-25".
Note : Initially date is in string format, after conversion whether it is in date or string format it doesn't matter.
file.js
function test (filepath) {
let date = "2020/02/25 23:58:08";
date = date.replace("//"/gi,"-");
// I am not familiar with regular expressions, I want to omit the data related to hours, seconds extra
}
When I ran the program, I gotUncaught ReferenceError: gi is not defined, gi is to globally replace
Try this
let date = "2020/02/25 23:58:08";
var date2 = new Date(date)
console.log(date2.toISOString().slice(0,10))
let date = `2020/02/25 23:58:08`;
let parsedDate = date.split(" ")[0].replace(/\//gi,'-');
console.log(parsedDate);
There is an error in the line using regex, should be:
let date = "2020/02/25 23:58:08";
date = date.replace(/\//gi,"-");
Then to get only the date, you can get the first 10 characters:
date.slice(0,10)
Final code:
let date = "2020/02/25 23:58:08";
date = date.replace(/\//gi,"-");
date.slice(0,10)
Although there are other ways to do it, you can use a library like momentJs which includes methods for this, like moment.format, it gives so many possibilities. But if you have a small case this is fine.
I am trying to extract the date from the following object (that has been stringified.)
I am new to regular expressions, and not sure how to go about it.
I tried /^(\d{4})\-(\d{1,2})\-(\d{1,2})$/gmi -> but it didnot work.
{"Date":"2016-05-16","Package Name":"com.myapp.mobile","Current Device Installs":"15912","Daily Device Installs":"41","Daily Device Uninstalls":"9","Daily Device Upgrades":"3","Current User Installs":"12406","Total User Installs":"23617","Daily User Installs":"27","Daily User Uninstalls":"8"}
Don't use a Regex here.
Do JSON.parse(str).Date, unless there is a really good reason not to (you haven't stated one in your question)
If you want to turn the string "2016-05-16" into 3 variables for Year, Month and day (without using a date library), I'd just use .split():
dateArray = "2016-05-16".split("-")
var year = dateArray[0], month = dateArray[1], day = dateArray[2];
Your regex matches fine, just don't use the /gmi flags
"2016-05-16".match(/^(\d{4})\-(\d{1,2})\-(\d{1,2})$/)
You can make it a bit simpler yet..
"2016-05-16".match(/(\d{4})-(\d{2})-(\d{2})/)
But, you really should be using a library for this, like moment.js, or at least Date which will work fine because this ISO-8601.
const date = new Date("2016-05-16");
date.getYear();
As suggested in comments, you can get the date by parsing the JSON (trimmed in the following for convenience):
var s = '{"Date":"2016-05-16","Package Name":"com.myapp.mobile"}';
var dateString = JSON.parse(s).Date;
document.write(dateString);
If you want a Date object, you can then parse the string. Note that using either the Date constructor or Date.parse for parsing strings is not recommended due to browser inconsistencies. Manually parsing an ISO date is fairly simple, you just need to decide whether to parse it as local or UTC.
Since ECMA-262 requires the date–only ISO format to be parsed as UTC, the following function will do that reliably (and return an invalid date for out of range values):
/* Parse an ISO 8601 format date string YYYY-MM-DD as UTC
** Note that where the host system has a negative time zone
** offset the local date will be one day earlier.
**
** #param {String} s - string to parse
** #returs {Date} date for parsed string. Returns an invalid
** Date if any value is out of range
*/
function parseISODate(s) {
var b = s.split(/\D/);
var d = new Date(Date.UTC(b[0], b[1]-1, b[2]));
return d && d.getMonth() == b[1]-1? d : new Date(NaN);
}
var d = parseISODate('2016-05-16');
document.write('UTC date: ' + d.toISOString() + '<br>' +
'Local date: ' + d.toString());
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Extending JavaScript's Date.parse to allow for DD/MM/YYYY (non-US formatted dates)?
Convert dd-mm-yyyy string to date
Entered a date in textbox, for example: 05/09/1985, and I wanted to convert it to 05-Sep-1985 (dd-MMM-yyyy) format. How would I achieve this? Note that the source format may be dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format.
Code Snippet:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val());
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
This code returns 09-May-1985 but I want 05-Sep-1985. Thanks.
You might want to use helper library like http://momentjs.com/ which wraps the native javascript date object for easier manipulations
Then you can do things like:
var day = moment("12-25-1995", "MM-DD-YYYY");
or
var day = moment("25/12/1995", "DD/MM/YYYY");
then operate on the date
day.add('days', 7)
and to get the native javascript date
day.toDate();
Update
Below you've said:
Sorry, i can't predict date format before, it should be like dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format finally i wanted to convert all this format to dd-MMM-yyyy format.
That completely changes the question. It'll be much more complex if you can't control the format. There is nothing built into JavaScript that will let you specify a date format. Officially, the only date format supported by JavaScript is a simplified version of ISO-8601: yyyy-mm-dd, although in practice almost all browsers also support yyyy/mm/dd as well. But other than that, you have to write the code yourself or (and this makes much more sense) use a good library. I'd probably use a library like moment.js or DateJS (although DateJS hasn't been maintained in years).
Original answer:
If the format is always dd/mm/yyyy, then this is trivial:
var parts = str.split("/");
var dt = new Date(parseInt(parts[2], 10),
parseInt(parts[1], 10) - 1,
parseInt(parts[0], 10));
split splits a string on the given delimiter. Then we use parseInt to convert the strings into numbers, and we use the new Date constructor to build a Date from those parts: The third part will be the year, the second part the month, and the first part the day. Date uses zero-based month numbers, and so we have to subtract one from the month number.
Date.parse recognizes only specific formats, and you don't have the option of telling it what your input format is. In this case it thinks that the input is in the format mm/dd/yyyy, so the result is wrong.
To fix this, you need either to parse the input yourself (e.g. with String.split) and then manually construct a Date object, or use a more full-featured library such as datejs.
Example for manual parsing:
var input = $('#' + controlName).val();
var parts = str.split("/");
var d1 = new Date(Number(parts[2]), Number(parts[1]) - 1, Number(parts[0]));
Example using date.js:
var input = $('#' + controlName).val();
var d1 = Date.parseExact(input, "d/M/yyyy");
Try this:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val().toString().replace(/([0-9]+)\/([0-9]+)/,'$2/$1'));
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
The RegExp replace .replace(/([0-9]+)\/([0-9]+)/,'$2/$1') change day/month position.
See this http://blog.stevenlevithan.com/archives/date-time-format
you can do anything with date.
file : http://stevenlevithan.com/assets/misc/date.format.js
add this to your html code using script tag and to use you can use it as :
var now = new Date();
now.format("m/dd/yy");
// Returns, e.g., 6/09/07
Given a date in the following string format:
2010-02-02T08:00:00Z
How to get the year with JavaScript?
It's a date, use Javascript's built in Date functions...
var d = new Date('2011-02-02T08:00:00Z');
alert(d.getFullYear());
You can simply parse the string:
var year = parseInt(dateString);
The parsing will end at the dash, as that can't be a part of an integer (except as the first character).
I would argue the proper way is
var year = (new Date('2010-02-02T08:00:00Z')).getFullYear();
or
var date = new Date('2010-02-02T08:00:00Z');
var year = date.getFullYear();
since it allows you to do other date manipulation later if you need to and will also continue to work if the date format ever changes.
UPDATED: Jason Benson pointed out that Date will parse it for you. So I removed the extraneous Date.parse calls.
var year = '2010-02-02T08:00:00Z'.substr(0,4)
...
var year = new Date('2010-02-02T08:00:00Z').getFullYear()
You can simply use -
var dateString = "2010-02-02T08:00:00Z";
var year = dateString.substr(0,4);
if the year always remain at the front positions of the year string.