Showing time in AM/PM from date time and resolve NAN issue

Intro:

if you get the date from the rest API and you need to show the time from that date with AM/PM, i think you should understand that what we are going to do, so let’s start the topic “Showing time in AM/PM from date time and resolve NAN issue“.

Output of is like –

Step 1: Now we are going to start the coding if you get the date format in this 2020-07-21 15:42:13 form and want to convert it to time AM/PM form.

Note: Date format updated_at: “2020-07-21 15:42:13” and after changing it —— Tue Jul 21, 2020, 15:42:13 GMT+0530 (India Standard Time)—-, then we get the time from this and convert it into AM/PM form.

render(
 return(){
  <Text> this.formatAMPM('2020-07-21 15:42:13')</Text>
 }
)

Step 2: Let’s provide the definition of formateAMPM().

here we are going to provide the definition of formateAMPM(), firstly we broke the date and create a new date formate then we get the hours and minutes from the date.

Now we check if the hour is greater than 12 then it’s PM or if it less than 12 then it should be AM.

Then we check if the minute is in a single digit then we add the ‘0’ at the start of minute, if you want to check the same thing in hours then you can check and append the ‘0’ here as well.

So here you find the code, firstly understand the code then copy and use it in your code.

formatAMPM(date) {
 var t = date.split(/[- :]/);
 var d = new Date(t[0], t[1] - 1, t[2], t[3], t[4], t[5]);
 var actiondate = new Date(d);
 var hours = actiondate.getHours();
 var minutes = actiondate.getMinutes();
 var ampm = hours >= 12 ? 'PM' : 'AM';
 hours = hours % 12;
 hours = hours ? hours : 12; // the hour '0' should be '12'
 minutes = minutes < 10 ? '0' + minutes : minutes;
 var time = hours + ':' + minutes + ' ' + ampm;
 return time;
}

This tutorial “Showing time in AM/PM from date time and resolve NAN issue” is completed now, you can find the next lesson here.

Please find my post on medium as well click here please follow me on medium.

And if any other query/issue, please feel free to ask.

Happy Coding Guyz.

Related Post