admin管理员组

文章数量:1302374

I have a string which is in the format "05-01-2016" when i run the below code in chrome i get the correct output

var fromDate = new Date(searchOpts.RunDateFrom);

        fromDate.format("yyyy-MM-dd");

output = "2016/05/01"

However, when this code is execute inside my js file i get this output

Sun May 01 2016 00:00:00 GMT+0530 (India Standard Time)

How do i prevent this? I need to pass the date in this format "2016-05-01" to solr

I have a string which is in the format "05-01-2016" when i run the below code in chrome i get the correct output

var fromDate = new Date(searchOpts.RunDateFrom);

        fromDate.format("yyyy-MM-dd");

output = "2016/05/01"

However, when this code is execute inside my js file i get this output

Sun May 01 2016 00:00:00 GMT+0530 (India Standard Time)

How do i prevent this? I need to pass the date in this format "2016-05-01" to solr

Share asked May 31, 2016 at 17:34 Ratan ServegarRatan Servegar 4151 gold badge7 silver badges24 bronze badges 5
  • Short answer: JavaScript's date handling is horrid. You have two options: Search StackOver for one of the dozens of questions on the topic -or- use momentjs. – Jeremy J Starcher Commented May 31, 2016 at 17:38
  • Possible duplicate of Format JavaScript Date to yyyy-mm-dd – Jeremy J Starcher Commented May 31, 2016 at 17:39
  • @Jeremy I can't use external libs, any other way? – Ratan Servegar Commented May 31, 2016 at 17:51
  • "Search StackOver for one of the dozens of questions on the topic" I linked to one already. – Jeremy J Starcher Commented May 31, 2016 at 18:01
  • @JeremyJStarcher Thanks – Ratan Servegar Commented May 31, 2016 at 18:09
Add a ment  | 

2 Answers 2

Reset to default 5
formattedDate = fromDate.getFullYear() + "-" + (fromDate.getMonth()+1) + "-" + fromDate.getDate()

If you just need the string

var year = fromDate.getFullYear();
var month = fromDate.getMonth() < 10 ? '0'+ fromDate.getMonth()+1 : fromDate.getMonth()+1

var date =  fromDate.getDate() < 10 ? '0'+ fromDate.getDate(): fromDate.getDate()

本文标签: Javascript convert string to date format yyyyMMddStack Overflow