简体   繁体   中英

How to convert string to date in react native with moment.js?

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!

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM