import React, { useState } from
'react'
;
import
'./App.css'
;
function
Converter() {
let [input_Time, set_Input_Time] = useState(
''
);
let [output_Time, set_Output_Time] = useState(
''
);
let [error_Msg, set_Error_Msg] = useState(
''
);
let [select_Format, set_Select_Format] = useState(
'to24'
);
let convertFunction = () => {
set_Error_Msg(
''
);
try
{
let hr, min, per;
if
(select_Format ===
'to24'
) {
[hr, min] = input_Time.split(
':'
);
hr = parseInt(hr, 10);
min = parseInt(min, 10);
if
(isNaN(hr) || isNaN(min) ||
hr < 0 || hr > 23 || min < 0 || min > 59) {
throw
new
Error(
'Invalid time format'
);
}
if
(hr === 12 && min === 0) {
set_Output_Time(`Time
in
12 Hour Format is: 12:00 AM`);
}
else
if
(hr >= 12) {
per =
'PM'
;
if
(hr > 12) {
hr -= 12;
}
set_Output_Time(`Time
in
12 Hour Format is:
${hr.toString().padStart(2,
'0'
)}:
${min.toString().padStart(2,
'0'
)}
${per}`);
}
else
{
per =
'AM'
;
if
(hr === 0) {
hr = 12;
}
set_Output_Time(`Time
in
12 Hour Format is:
${hr.toString().padStart(2,
'0'
)}:
${min.toString().padStart(2,
'0'
)}
${per}`);
}
}
else
if
(select_Format ===
'to12'
) {
let [time, givenPeriod] = input_Time.split(
' '
);
if
(!time) {
throw
new
Error(
'Invalid input format'
);
}
[hr, min] = time.split(
':'
);
hr = parseInt(hr, 10);
min = parseInt(min, 10);
if
(isNaN(hr) || isNaN(min) || min < 0 || min > 59) {
throw
new
Error(
'Invalid time format'
);
}
if
(givenPeriod ===
'AM'
|| givenPeriod ===
'PM'
) {
if
(hr === 12) {
hr = givenPeriod ===
'AM'
? 0 : 12;
}
else
if
(givenPeriod ===
'PM'
) {
hr += 12;
}
}
else
{
throw
new
Error(
'Invalid input format'
);
}
set_Output_Time(`Time
in
24 Hour Format is:
${hr.toString().padStart(2,
'0'
)}:
${min.toString().padStart(2,
'0'
)}`);
}
}
catch
(err) {
set_Error_Msg(
'Invalid input. Please enter a valid time in the specified format.'
);
set_Output_Time(
''
);
}
};
return
(
<div className=
"converter-container"
>
<h1 className=
'app-title'
>
GeeksforGeeks
</h1>
<h2 className=
"converter-title"
>
Time Converter
</h2>
<div className=
"input-group"
>
<label className=
"label"
>
Enter Time (
{select_Format ===
'to24'
?
'24-Hour'
:
'12-Hour'
} Format)
</label>
<input
type=
"text"
className=
"form-control"
value={input_Time}
onChange={(e) => set_Input_Time(e.target.value)}
placeholder={`e.g.,
${select_Format ===
'to24'
?
'14:30'
:
'02:30 PM'
}`}
/>
</div>
<div className=
"input-group"
>
<label className=
"label"
>
Select Time Conversion Format
</label>
<select
className=
"form-select"
value={select_Format}
onChange={(e) =>
set_Select_Format(e.target.value)}
>
<option value=
"to24"
>
24-Hour to 12-Hour
</option>
<option value=
"to12"
>
12-Hour to 24-Hour
</option>
</select>
</div>
<button className=
"convert-button"
onClick={convertFunction}>
Convert
</button>
{error_Msg && <div className=
"error"
>
{error_Msg}
</div>}
{output_Time &&
<div className=
"result"
>
{output_Time}
</div>}
</div>
);
}
export
default
Converter;