将军事时间改为标准时间的程序

时间:2016-12-01 02:42:57

标签: java time format

    public class Time
    {
      private int time = 1200;
      private int hour = 00;
      private int minute = 00;

       public Time ()
      {
        time = 1200;

      }

      public Time (int h, int m)
      {
        hour = h;
        minute= m;

      }

      public String toString()
      {
        hour =time % 1000; 

        return hour;
      }
  }

我想知道如何使用模数将两位数设置为小时变量。

1 个答案:

答案 0 :(得分:1)

如果您想使用Java的一些内置功能,例如DateSimpleDateFormat,您可以执行以下操作:

import java.util.Scanner;
import java.text.SimpleDateFormat;
import java.util.Date;

class Main {
  public static void main(String[] args) {
    System.out.println("James Mathis's 24-hour (Miltary) to 12-hour time converter");
    System.out.println("==========================================================");
    System.out.print("Please enter a 24 time in the format hh:mm (example: 13:45):");

    Scanner scanIn = new Scanner(System.in);
    String input24Time = scanIn.nextLine();
    scanIn.close();
    System.out.println("24-hour (Military) Time entered: " + input24Time);

    try {
      final SimpleDateFormat sdf = new SimpleDateFormat("H:mm");
      final Date dateObj = sdf.parse(input24Time);
      String timein12Format = new SimpleDateFormat("K:mm a").format(dateObj);
      System.out.println("The equivalent 12 hour time is: " + timein12Format);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

试试here!