kingofjong
kingofjong

Reputation: 175

Why do I get an error with Date formatting in sapUI5?

I get the error message Uncaught TypeError: Cannot read property 'group' of undefined when formatting a date in my UI5 code. I have tried using pattern and oDate.parse() but that doesn't return the date in MM/DD/yyyy HH:mm:ss format.

Here is the function that is doing the formatting

getSomeDate: function (sDate) {
      var oDate = DateFormat.getDateTimeInstance({
          format: "MM/DD/yyyy HH:mm:ss",
          source: {
              pattern: 'YYYYMMDDhhmmss'
          }

      });
return oDate.format(sDate);
},

The expected result is date in the format MM/DD/yyyy HH:mm:ss.

Upvotes: 0

Views: 2705

Answers (3)

Karsten Voigt
Karsten Voigt

Reputation: 71

if you want to use a specific pattern for formatting a date, you should use the "pattern" property. This will format your date according to the defined pattern.

The format property only allows pattern symbols. If you use a symbol that is not a valid pattern; you'll get the error "Cannot read property 'group' of undefined".

From the spec:

The format string does contain pattern symbols (e.g. yMMMd or Hms) and will be converted into the pattern in the used locale, which matches the wanted symbols best. The symbols must be in canonical order, that is: Era (G), Year (y/Y), Quarter (q/Q), Month (M/L), Week (w/W), Day-Of-Week (E/c), Day (d/D), Hour (h/H/k/K), Minute (m), Second (s), Timezone (z/Z/v/V/O/X/x).

So if you use format the "system" tries to format the passed date according to current user settings. Using pattern will strictly follow your defined pattern.

Regards

Upvotes: 0

Cmdd
Cmdd

Reputation: 897

If you want to format a date string you should use a DateTime type.

getSomeDate: function (sDate) {
      var oType = new sap.ui.model.type.DateTime({
                pattern: "MM/dd/yyyy hh:mm:ss",
                source: {
                    pattern: "yyyyMMddhhmmss"
                }
            });

      return oType.formatValue(sDate, "String");
},

Upvotes: 0

Vivek K C
Vivek K C

Reputation: 1

Expected date format : MM/DD/yyyy HH:mm:ss.
Source date format: new Date() object

getSomeDate: function (sDate) {
      var oDate = DateFormat.getDateTimeInstance({
          pattern: 'MM/dd/yyyy hh:mm:ss
      });
return oDate.format(sDate);
}

If you directly want to try this out in console, you can use below code.

function getSomeDate(sDate) {
      var oDate = sap.ui.core.format.DateFormat.getDateTimeInstance({
         pattern: 'MM/dd/yyyy hh:mm:ss'
      });
console.log(oDate.format(sDate));
}

getSomeDate(new Date());

Upvotes: 0

Related Questions