Moment localization not considering time while formating date?

616 views Asked by At

function formatedDate (localid, inputdate) {
 var locale = 'es_MX';
     console.log(locale, inputdate)
     // Set locale to moment
      moment.locale(locale);
     // Get locale data
     const localeData = moment.localeData(locale);
     const format = localeData.longDateFormat('L');
     const m2 = moment(new Date(inputdate), format);
     console.log(m2.format());
     console.log(m2.format(format) + ' using format: ' + format);
return m2.format(format)
};

 

console.log(formatedDate('ex-MX', '2020-10-07T06:02:55Z'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>

I need to convert dates according to the country/area , it depends completely base on location.

So I am trying to achieve this by using moment js

Here dates are stores in UST format in database

Example: If Input ''2020-10-07T09:30:00'

expected Output for 06/10/2020

Here date is formatting according to the locale but it not considering time, all regions it showing same date in different formats, based on time and locale it should format..

Note: I only need to display date (but while formatting time should consider)

In my angular application it not working as expected What I am doing wrong ,, Can any one help me .

Thanks in advance

2

There are 2 answers

2
Akash On

Locale does not relate to a timezone because one locale may belong to multiple timezones. For example, en-US has 6 timezones. So I don't think passing a locale will convert your date to the expected timezone.

You can use DatePipe provided by angular for formatting and timezone conversions.

If your date is in UST, you can convert it to UTC by adding 4 hours. Then convert it to your required timezone -

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
 zone = 'IST';
 locale = 'en-US'; 
 currentDate = '';
  constructor(private date: DatePipe) {

  }
  getTime() {
    // Date is in UTC (suffix z)
    const d = this.date.transform('2020-10-07T09:30:00Z', 'short', this.zone, this.locale);
    console.log(d);
    this.currentDate = d;
  }

Please see this example.

Note:

I am not sure if you have the timezone available, but you can always get it if you know the location (see this answer).

2
muhammad thahir On
function formatedDate (localid, inputdate) {
     const local = moment(inputdate).locale(localid)
     return local.format('L')
};

 

console.log(formatedDate('ex-MX', '2020-10-07T06:02:55Z'));

if you want local time based on timezone, use moment-timezone

   function formatedDate(date,timezone){
      return moment.tz(date,timezone).format('LLLL');
   }