skip to Main Content

So basically I want to convert my time from 24 hour format to 12 hour format, I tried using this code below to do it but it just does not work what am I missing

what else should I do to make it work. please let me know thanks

import React, { useState, useEffect } from 'react';
import styled from "styled-components";
import io from 'socket.io-client';

const ScanCounterTime = ({parcelCount}) => {
    function tConvert (time) {
        // Check correct time format and split into components
        time = time.toString ().match (/^([01]d|2[0-3])(:)([0-5]d)(:[0-5]d)?$/) || [time];
      
        if (time.length > 1) { // If time format correct
          time = time.slice (1);  // Remove full string match value
          time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM
          time[0] = +time[0] % 12 || 12; // Adjust hours
        }
        return time.join (''); // return adjusted time or original string
      }
      
    // useState accepts an initial state and returns two values:
    //1. The current state
    //2. A function that updates the state
    // thats why theres currentTime and setCurrentTime basically it should 
    // show something like 2 - 3 for example 
    const [currentTime, setCurrentTime] = useState(new Date().getHours());

    const updateCurrentTime = () => {
        // this will get the current hour 
        const currentHour = new Date().getHours();
        // this will get the next hour %24 to prevent it from going above it 
        const nextHour = (currentHour + 1) % 24;
        // expression interpolation to store the currentTime and nextHour kinda like pythons format function 
        const hey = tConvert(currentHour);
        const bye = tConvert(nextHour);
        const formattedTime = `${hey} - ${bye}`;
        setCurrentTime(formattedTime);
    };
    useEffect(() => {
        const intervalId = 
            setInterval(() => {
                updateCurrentTime()
            },1000); 
        return () => clearInterval(intervalId);
    }, [])
    
    return (
        <div>
            <StyledRectangle>
            <div></div>
            <TimeText>{currentTime}</TimeText>
            </StyledRectangle>
        </div>
    );
};


const StyledRectangle = styled.div`
  width: 134.02px;
  height: 87.17px;
  background-color: gray;
  box-shadow: 8px 8px 17px rgba(66, 61, 61, 0.25);
  border-radius: 20px;
  padding: 4rem;
`;

const TimeText = styled.span`
  color: white; 
  font-size: 15px;
  font-family: Aeonik;
  text-align: center;
`;

export default ScanCounterTime;


it shows the time in 24 hour but the function I created to convert it does not work.

2

Answers


  1. There’s an issue in your tConvert function where you’re not correctly handling the time formatting. The regex match might not be giving you the expected results. Let’s revise your tConvert function to handle the 24-hour format correctly:

    function tConvert(time) {
        // Extract hours, minutes, and seconds from the time string
        const [hours, minutes, seconds] = time.split(':');
    
        // Convert hours to a number
        let hour = parseInt(hours);
    
        // Determine if it's AM or PM
        const meridiem = hour >= 12 ? 'PM' : 'AM';
    
        // Convert to 12-hour format
        hour = hour % 12 || 12;
    
        // Format the time string
        const formattedTime = `${hour}:${minutes}:${seconds} ${meridiem}`;
        console.log(formattedTime); // Log the formatted time
        return formattedTime;
    }
    tConvert('13:30:00'); // Example time in 24-hour format
    Login or Signup to reply.
  2. Since your data source is a Date object, there isn’t any "conversion" going on, only "rendering". You can render a Date into human-readable string using Intl.DateTimeFormat, which gives you plenty of options.

    const date = new Date();
    const hour = new Intl.DateTimeFormat("en-US", {
      hour: "numeric",
      hour12: true,
    }).format(date);
    console.log(hour);

    Remember: When working with date-time values, always manipulate them in raw value (i.e. unix timestamp, Date object is essentially a wrapper of unix timestamp), only render it to human-readable string (with format and timezone) at the very last step when display to user is needed. In reverse, if you get a formatted date-time string as a data source, always parse it to unix timestamp before any manipulation. Never manipulate date-time as a string.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search