All files / web/bundles/pimui/js/formatter date-formatter.js

100% Statements 11/11
85.71% Branches 6/7
100% Functions 2/2
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62                    368x                     368x                                           287x 127x     160x 160x   160x 160x 160x 160x     160x          
'use strict';
 
/**
 * Format a date according to specified format.
 * It instantiates a datepicker on-the-fly to perform the conversion.
 *
 * @author    Willy Mesnage <willy.mesnage@akeneo.com>
 * @copyright 2016 Akeneo SAS (http://www.akeneo.com)
 * @license   http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */
define([
        'jquery',
        'underscore',
        'datepicker',
        'pim/date-context'
    ], function (
        $,
        _,
        Datepicker,
        DateContext
    ) {
        return {
            /**
             * Date widget options
             */
            datetimepickerOptions: {
                format: DateContext.get('date').format,
                defaultFormat: DateContext.get('date').defaultFormat,
                language: DateContext.get('language')
            },
 
            /**
             * Format a date according to specified format.
             * It instantiates a datepicker on-the-fly to perform the conversion. Not possible to use the "real"
             * ones since we need to format a date even when the UI is not initialized yet.
             *
             * @param {String} date
             * @param {String} fromFormat
             * @param {String} toFormat
             *
             * @return {String}
             */
            format: function (date, fromFormat, toFormat) {
                if (_.isEmpty(date) || _.isUndefined(date) || _.isArray(date)) {
                    return null;
                }
 
                var options = $.extend({}, this.datetimepickerOptions, {format: fromFormat});
                var fakeDatepicker = Datepicker.init($('<input>'), options).data('datetimepicker');
 
                Eif (null !== fakeDatepicker.parseDate(date)) {
                    fakeDatepicker.setValue(date);
                    fakeDatepicker.format = toFormat;
                    fakeDatepicker._compileFormat();
                }
 
                return fakeDatepicker.formatDate(fakeDatepicker.getDate());
            }
        };
    }
);