Friday, September 11, 2015

Time Conversion

Problem Statement

You are given time in AM/PM format. Convert this into a 24 hour format.

Note Midnight is 12:00:00AM or 00:00:00 and 12 Noon is 12:00:00PM.

Input Format

Input consists of time in the AM/PM format i.e. hh:mm:ssAM or hh:mm:ssPM
where
01≤hh≤12
00≤mm≤59
00≤ss≤59

Output Format

You need to print the time in 24 hour format i.e. hh:mm:ss
where
00≤hh≤23
00≤mm≤59
00≤ss≤59



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);
  String s = "07:05:45PM";
  DateFormat inFormat = new SimpleDateFormat( "hh:mm:ssaa");
  DateFormat outFormat = new SimpleDateFormat( "HH:mm:ss");

  Date date = null;
  try {
   date = inFormat.parse(s); 
  }catch (ParseException e ){
   e.printStackTrace();
  }
  if( date != null ){
   String myDate = outFormat.format(date);
   System.out.println(myDate);
  }
 }

}

No comments:

Post a Comment