NewToJS
NewToJS

Reputation: 2101

How to parse a date like '2009-09-13' in D3.JS or moment

I have several dates as strings that are in the format: YYYY-MM-DD. So for example:

var origDate = '2009-09-13'

I want to parse them so that they're just written out as month (abbreviated or full month), day, year like: Sept. 9, 2009

..Is there a way to do this in D3.JS or Moment.JS?

Right now I'm using this D3 formula to parse the dates:

var format = d3.time.format("%Y-%m-%d").parse;

But when I do: format(origDate), I get really long dates like: enter image description here

Upvotes: 1

Views: 1642

Answers (3)

gyre
gyre

Reputation: 16777

Vanilla JS

Use the new Date constructor on your string (it is in a supported format), and then use a format function to map each month to its abbreviation and include other information.

var abbr = 'Jan. Feb. Mar. Apr. May June July Aug. Sept. Oct. Nov. Dec.'.split(' ')

function format (date) {
  return abbr[date.getUTCMonth()] + ' ' + date.getUTCDate() + ', ' + date.getUTCFullYear()
}

var origDate = '2009-09-13'

console.log(
  format(new Date(origDate))
)

Moment.js

Moment.js objects have a format function that takes a format string. For the full list of parameters you can use, see the documentation on displaying.

var origDate = '2009-09-13'

console.log(
  moment.utc(origDate).format('MMM. D, YYYY')
)
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>

Upvotes: 1

Andrew Reid
Andrew Reid

Reputation: 38211

Is there a way to do this in D3.JS?

Yes. Your line

var format = d3.time.format("%Y-%m-%d").parse;

is creating a date object. You need to apply formatting to the object to get the desired output string:

// working date:
var string = '2009-05-01';

// set up a format
var format = d3.time.format("%Y-%m-%d");

// convert the date string into a date object:
var date = format.parse(string);

// output the date object as a string based on the format:
console.log(format(date));

// use the desired format
var format1 = d3.time.format("%B %d, %Y");

// output a date as a string in the desired format
console.log(format1(date));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Upvotes: 2

Nelson Teixeira
Nelson Teixeira

Reputation: 6610

Using moment do it like this:

var origDate = '2009-09-13'

mDate = moment(origDate);

console.log(mDate.format("DD/MM/YYYY"));

https://jsfiddle.net/0p2c6zjo/

Upvotes: 1

Related Questions