Home > Software design >  How to convert string to date in react native with moment.js?
How to convert string to date in react native with moment.js?

Time:09-29

I have this date in string, now i want to convert this with UTC using moment.js.

Wednesday, 22 September 2021, 7:00:00 am

Expected result:

Formate: DD-MMM-YYYY hh:mm a

Date: 22-Sep-2021 12:30 PM

I tried this way but not working

let dateStr = 'Wednesday, 22 September 2021, 7:00:00 am'
utcDate = moment(moment(dateStr, 'DD-MMM-YYYY hh:mm a'))
  .utc()
  .format('DD MMM YYYY, hh:mm A');

Also I tried this conversion with dayjs but it works well in iOS but not in Android where I get null.

utcDate = dayjs(new Date(`${dateStr} UTC`)).format(
  'DD MMM YYYY, hh:mm A',
);

let me know if anyone have solution for this.

Thanks!

CodePudding user response:

You need to remove the format from moment call.

You can do this but it is a deprecated way

let dateStr = 'Wednesday, 22 September 2021, 7:00:00 am'
// You can do this but it is deprecated way
const date = moment(dateStr)
  .utc()
  .format('DD MMM YYYY, hh:mm A');

console.log(date)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

The better solution.

let dateStr = 'Wednesday, 22 September 2021, 7:00:00 am'
const date = moment(new Date(dateStr))
  .utc()
  .format('DD MMM YYYY, hh:mm A');

console.log(date)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

CodePudding user response:

Try this:

let dateStr = 'Wednesday, 22 September 2021, 7:00:00 am'
const utcDate = moment(new Date(dateStr))
  .utc()
  .format('DD MMM YYYY, hh:mm A');

console.log(utcDate)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8 M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

  • Related