display day and month, without a year according to locale

前端 未结 4 602
灰色年华
灰色年华 2020-12-12 03:17

Is there any better way for getting only day and month from a date including location appropriate separator?

I have a solution that gets separator first:

4条回答
  •  甜味超标
    2020-12-12 03:55

    Have you considered using Date#toLocaleDateString instead of monentjs?

    It takes a JS Date object and options to output a locale date in the format you specify.

    Example:

    var date = new Date();
    var options = { day: 'numeric', month: 'short' };
    
    console.log(date.toLocaleDateString('en-GB', options));
    // outputs: Feb 24
    
    var numeric = { day: 'numeric', month: 'numeric' };
    
    console.log(date.toLocaleDateString('en-GB', numeric));
    // outputs: 24/02
    

    As pointed out in the comments, it's worth ensuring that your targeted platforms support the toLocaleDateString approach above with options. For instance, this approach isn't currently supported by Android webview as detailed here for toLocaleDateString's Browser_compatibility

提交回复
热议问题