In my mean stack app, i have data on a date basis. In angular side, i used a date picker to get/set the date that the read/write of Data to be handled. The date picker produce date of the form "dd-mm-yyyy". What is the easiest way to convert this into mongodb understandable format, and back.
Asked
Active
Viewed 1.7k times
6
-
2https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString – Teemu Jan 17 '16 at 09:09
-
toISOString() will produce the ISO string from a Date object. So how to convert a date like 29-8-2014 into the date object. – ISONecroMAn Jan 17 '16 at 09:17
-
On the left-side of the page I've linked, there's a bunch of links to Date object documentation ... See also http://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript – Teemu Jan 17 '16 at 09:36
-
i added a verbose solution.. – ISONecroMAn Jan 17 '16 at 12:14
-
Can you make the datepicker produce the date as `yyyy-mm-dd` string instead? – Yaron Schwimmer Jan 17 '16 at 14:11
-
i am using a library, mero ui css, it's very rich and there are all kind of date pickers available. But for me dd-mm-yyyy string is the most natural and comfortable. – ISONecroMAn Jan 17 '16 at 16:35
-
I believe Date objects in Javascript are formed using YYYY-mm-dd as default. You may have to manipulate the your entry format before converting. – mluke Apr 28 '17 at 13:01
2 Answers
7
var str = "29-1-2016";
darr = str.split("-"); // ["29", "1", "2016"]
var dobj = new Date(parseInt(darr[2]),parseInt(darr[1])-1,parseInt(darr[0]));
// Date {Fri Jan 29 2016 00:00:00 GMT+0530(utopia standard time)
console.log(dobj.toISOString());
//2016-01-28T18:30:00.000Z
This will do it, but is there an easier way..!!
- Also please comment on why in the isodate format i get 2016-01-28T...., other than 2016-01-29T.....

ISONecroMAn
- 1,460
- 2
- 16
- 23
1
You could use this solution (worked in my case)-
Firstly, use Moment.js in your code, include it in your project. Now, The time string that you are getting here var str = "29-1-2016";
and along with moment.js use the below code and you're good to go -
var str = "29-1-2016";
var time = moment(str).toISOString();
\\ This variable time is now converted into ISO string

HardikT
- 735
- 1
- 8
- 24
-
-
`2016-01-29` (`yyyy-mm-dd`) works, so it doesn't answer OP's question – Shaya Ulman May 27 '20 at 12:47