-4

I have a string value and i need to convert that string value to the following date format using javascript.

var strDate = "2016-11-20";

expected output is: 20-Nov-2016

How Can I change this?

Aravi2706
  • 1
  • 2
  • There are [*many duplicates*](https://stackoverflow.com/search?q=%5Bjavascript%5D+reformat+date+string). – RobG Aug 21 '17 at 06:32

2 Answers2

0

javascript have rich set of Date function e.g.:

new Date();

new Date(value);

new Date(dateString);

new Date(year, month[, date[, hours[, minutes[, seconds[, milliseconds]]]]]);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

also already answered here : Converting string to date in js

I have a UTC string and I want to convert it to UTC Date Object in JavaScript

We can mark this question duplicate

  • If it's a duplicate, mark it, though I disagree with the one you've marked. There are many duplicates for reformatting a **string**. Please don't post comments as answers. – RobG Aug 21 '17 at 06:37
-1

A little workaround could be the following, but if you have to manipulate dates a lot, I strongly recommend you to use the Moment.js library:

https://momentjs.com/

var strDate = "2016-11-20";
var utcDate = new Date(strDate).toUTCString();
var convertedDate= utcDate.substring(utcDate.lastIndexOf(", ") + 1, utcDate.lastIndexOf(" 00:"));
console.log(convertedDate.trim().replace(/\s/g, '-'));

Pay attention that the implementation of this method may change depending on the platform. Here from the official doc:

The value returned by toUTCString() is a human readable string in the UTC time zone. The format of the return value may vary according to the platform. The most common return value is a RFC-1123 formatted date stamp, which is a slightly updated version of RFC-822 date stamps.

quirimmo
  • 9,800
  • 3
  • 30
  • 45
  • But its shows 20 Nov 2016 but the expectation is 20-Nov-2016 – Aravi2706 Aug 20 '17 at 14:07
  • [*toUTCString*](http://ecma-international.org/ecma-262/8.0/#sec-date.prototype.toutcstring) is implementation dependent, it does not necessarily return the string in the required format. – RobG Aug 21 '17 at 06:30
  • @RobG Thanks for pointing that out. Absolutely correct. Updated the answer to explain that as well. – quirimmo Aug 21 '17 at 10:14