1

I am getting a date in some format ('yyyymmdd' or 'yyyymm') and need to display it as a string in my current locale.

For this example, the locale is 'en-GB'.

When I get the full format(yyyymmdd), I am presetting dd/mm/yyyy, and if it is partial(yyyymm) I need to display mm/yyyy, but I get 01/mm/yyyy, how can I solve it?

this is my function-

getDateStrFromEsploro(date: string){
    if (date.length === 8){
        const year = date.substring(0,4);
        const month = date.substring(4,6);
        const day = date.substring(6);
        return DateUtils.getDateAsString(new Date(parseInt(year), parseInt(month)-1, parseInt(day)));
    } else if (date.length === 6){
        const year = date.substring(0,4);
        const month = date.substring(4,6);
        return DateUtils.getDateAsString(new Date(parseInt(year), parseInt(month)-1));
    }
}

My DateUtils-

public static getDateAsString(date: Date) {
    return date.toLocaleDateString();
}
Pritesh
  • 1,066
  • 3
  • 15
  • 35
danda
  • 553
  • 10
  • 30
  • *parseInt* is unnecessary in `new Date(parseInt(year), parseInt(month)-1, parseInt(day)`. ;-) – RobG Aug 19 '19 at 06:39

2 Answers2

3

Using toLocaleDateString() options parameter

// without options
console.log(new Date(2019, 7).toLocaleDateString('en-GB'))

// with options
let date = new Date(2019, 7).toLocaleDateString('en-GB', {
  year: 'numeric',
  month: 'numeric',
});

console.log(date)
User863
  • 19,346
  • 2
  • 17
  • 41
1

You can skip the loop by checking the length

const date1 = [2019, 8];
const date2 = [2019, 8, 7];
const dateString = (date) => new Date(...date).toLocaleDateString('en-GB', {
  day: date.length === 2 ? undefined : 'numeric',
  year: 'numeric',
  month: 'numeric',
});

console.log(dateString(date1));
console.log(dateString(date2));
acesmndr
  • 8,137
  • 3
  • 23
  • 28
  • 1
    In Safari, this returns *Invalid Date* for both dates. See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results). `new Date([2019, 8])` is not consistent with the formats supported by ECMA-262, nor are the arrays consistent with the OP's data. – RobG Aug 19 '19 at 06:57
  • @RobG Added destructuring to pass in the date. I see the OP parsed the date from the string using a custom function thus added this solution. – acesmndr Aug 19 '19 at 07:30