I want to convert 20170603 into a date. I want to use the function new Date(2017,06,03), but how do I extract the numbers from the date? I tried using
new Date(parseInt(startDate.substr(0,4)), parseInt(startDate.substr(5,6)) -1, parseInt(startDate.substr(6,8)))
However, this gives me very weird values. How do I extract the exact numbers into the Date function?
Second parameter of substr function is length of string you want to extract;
new Date(parseInt(startDate.substr(0,4)),
parseInt(startDate.substr(4,2)) - 1,
parseInt(startDate.substr(6,2)));
substr Method (String) (JavaScript)
Using replace() with RegExp
const date_str = "20170603";
console.log( new Date( date_str.replace( /(\d{4})(\d{2})(\d{2})/, "$1/$2/$3" ) ) );
If using an external library is not an issue. I would suggest using moment.js
There are many methods available. For your case.
var d = new moment("20170603 ", "YYYYMMDD").toDate();
I am using this lib to solve a lot of challenges.
Slicing by character counts:
new Date(my_str.match(/(....)(..)(..)/).slice(1,4).join('/'))
Related
Let's say I have a array of date strings,
const a = ["11/23/2018","10/22/1992","02/02/1993","01/01/1990",...];
const b = ["12/01/2018","12/12/1992","24/09/1993","16/01/1990",...];
is there way to identify data format of each of these arrays, like
a => MM/DD/YYYY
b => DD/MM/YYYY
in javascript. I am not looking for a solution in vanila javascript, if you can point me to a solution using momentjs or date-fns It would be fine.
thank you, in advance.
As stated in the comments, you can use momentjs Parse Date Format plug-in.
This plug-in add the parseFormat method:
That allows to create smart date inputs that let your users set a Date/Time and lets you extract the user's preferred format for future usage.
parseFormat method accepts preferredOrder options to customize plug-in results for ambigous inputs. You can use preferredOrder and your own logic to get your desired result.
Here an example of a function that returns the most frequent format in the array with extracted with default parseFormat behaviour:
const a = ["11/23/2018","10/22/1992","02/02/1993","01/01/1990"];
const b = ["12/01/2018","12/12/1992","24/09/1993","16/01/1990"];
function getFormat(arr){
return arr.map((elem) => moment.parseFormat(elem))
// get most frequent element from here: https://stackoverflow.com/a/20762713/4131048
.sort((a,b) =>
arr.filter(v => v===a).length
- arr.filter(v => v===b).length
).pop();
}
console.log( getFormat(a) );
console.log( getFormat(b) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>
<script src="https://gr2m.github.io/moment-parseformat/moment-parseformat.js"></script>
I am currently having some challenge in converting String data type to Date type. I used the MarkLogic JavaScript function xdmp.parseDateTime, but I am always getting the error below:
Scenario: Convert "2013-04-21" (string) to 2013-04-21 (date type)
Code:
let targetDateString = "2013-04-21";
let targetDate = new Date();
targetDate = xdmp.parseDateTime("[Y0001]-[M01]-[D01]",
xs.date(targetDate));
Error Info:
XDMP-ARGTYPE: xdmp.parseDateTime("[Y0001]-[M01]-[D01]", xs.date("2013-04-21")) -- arg2 is not of type String
Am I using the right MarkLogic function, supplying the right parameters to it?
Or is there a better way to do it?
And how do I cast a date back to a string data type?
xs.date("2013-04-21") is the xquery date constructor (ported to JS), taking a string and returning an xs:date. xs.dateTime("2013-04-21T00:00:00") would get you an xs:dateTime.
xdmp.parseDateTime can turn a string to xs:dateTime from more formats, the second term is a string: xdmp.parseDateTime("[Y0001]-[M01]-[D01]", targetDateString)
See https://docs.marklogic.com/xdmp.parseDateTime
Converting back to a string is just fn.string(yourdate)
you can directly use the constructor of date class.
var d = new Date("2013-04-21");
console.log(d);
you can even use it with different formats, Ref.
This is a string 2011-11-09 00:00:00
So now how do I separate the date i.e. 2011-11-09 from the string, I dont want to use the slicing here if anyone has better options or ideas please let me know..
var date = '2011-11-09 00:00:00'.split(' ')[0];
You can split it by ' ' and then the first element will contain what you want.
console.log('2011-11-09 00:00:00'.split(' ')[0]);
Like this:
var date = 'This is a string 2011-11-09 00:00:00'.match(/\d{4}-\d{2}-\d{2}/)
if you dont want to use splicing, like you posted you could create a Date obj
var newDate = new Date(2011-11-09 00:00:00);
then to get the date, just use the toString override
var dateOnly = newDate.toString("YYYY-mm-dd");
That is if you dont want to use splicing or splits
I want to develop a JavaScript function to calculate the activity of users based on the date in the server where the data is stored. The problem is that the date is a string like this:
2013-08-11T20:17:08.468Z
How can I compare two string like this to calculate minor and major time as in the example?
If you want to compare two dates just use this :
var dateA = '2013-08-11T20:17:08.468Z';
var parsedDateA = new Date(dateA).getTime();
var dateB = '2013-06-06T17:33:08.468Z';
var parsedDateB = new Date(dateB).getTime();
if(parsedDateA > parsedDateB) {
// do something
}
Assuming you need to do the comparisons client-side, the best way is to load the dates into Date objects using Date.parse. Then compare them using the functions provided for Date, such as getTime.
Try parse method:
var s = "2013-08-11T20:17:08.468Z";
var d = Date.parse(s);
As I have understood you in the right way, there is a good answer to your question here.
You can also look at this very good Library (DateJS).
If your problem was converting from the Date-String to js-Date look at this Page.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Simplest way to parse a Date in Javascript
I understand how do get the data and break it down into it's segments, i.e.
alert( ( new Date ).getDate() );
and
alert( ( new Date ).getFullYear() );
alert( ( new Date ).getFullMonth() );
etc etc.
But how do I do the same but use a date from a html textbox? instead of reading new Date?
The date in the HTML box would be formated as follows
31/10/2012
You could try:
var datearray = input.value.split("/");
var date = new Date(datearray[2],datearray[1] - 1,datearray[0])
If your textbox has proper string format for a date object you can use:
var aDate = new Date($("textbox").val());
However, if you dont write it in the text box exactly as you would in a string passing to the object, you'll get null for your variable.
FYI, I made a plugin that "extends" the Date object pretty nicely and has preformatted date/times that include things like a basic SQL datetime format.
Just go to this jsFiddle, Copy the code between Begin Plugin and End Plugin into a js file and link it in your header after your jQuery.
The use is as simple as above example:
var aDate = new DateTime($("textbox").val());
And to get a specific format from that you do:
var sqlDate = aDate.formats.compound.mySQL;