Search code examples
momentjsbreeze

Breeze: Date Formatting


I'm receiving dates from the server in this format: Thu Apr 25 16:47:10 UTC+0200 2013.

The type is Date.

I want dates to be displayed in the DD/MM/YYYY format. So I've used Moment.js and in the initializer function of my entity, called from registerEntityTypeCtor, I do:

myEntity.CreatedDate = moment.utc(myEntity.CreatedDate).format('DD/MM/YYYY');

Although that code returns the properly formatted date, myEntity.CreatedDate remains the same. Actually if I inspect in the Visual Studio debugger and I expand the property, it says 'prototype: Invalid Date'.

I have two questions:

  1. Am I doing it the right way ? i.e, it it a good thing to do the conversion in the registerEntityTypeCtor?
  2. Why is it not working :-) ?

Solution

  • Breeze dates are javascript dates. What you are doing is setting a date property with a string. Breeze then attempts to parse the string, via javascript's Date.parse method, into a date in order to validate it. If this fails, Breeze just leaves it alone.

    In general, if you want to format any date properties, this should not be done in the model, but rather in the view. In other words, wherever you are displaying the dates, that is the best location to convert the dates into strings. If you are using a binding library like ko or angular, both provide mechanisms for doing this, as do most javascript template engines.