Как написать конвертер времени на java

We can solve this by using String Buffer
String s;

static String timeConversion(String s) {
   StringBuffer st=new StringBuffer(s);
   for(int i=0;i<=st.length();i++){

       if(st.charAt(0)=='0' && st.charAt(1)=='1' &&st.charAt(8)=='P' ){
        //    if(st.charAt(2)=='1'){
               // st.replace(1,2,"13");
                st.setCharAt(0, '1');
                st.setCharAt(1, '3');
       }else if(st.charAt(0)=='0' && st.charAt(1)=='2' &&st.charAt(8)=='P' ){
        //    if(st.charAt(2)=='1'){
               // st.replace(1,2,"13");
                st.setCharAt(0, '1');
                st.setCharAt(1, '4');
        }else if(st.charAt(0)=='0' && st.charAt(1)=='3' &&st.charAt(8)=='P' ){
        //    if(st.charAt(2)=='1'){
               // st.replace(1,2,"13");
                st.setCharAt(0, '1');
                st.setCharAt(1, '5');
         }else if(st.charAt(0)=='0' && st.charAt(1)=='4' &&st.charAt(8)=='P' ){
        //    if(st.charAt(2)=='1'){
               // st.replace(1,2,"13");
                st.setCharAt(0, '1');
                st.setCharAt(1, '6');
         }else if(st.charAt(0)=='0' && st.charAt(1)=='5' &&st.charAt(8)=='P' ){
        //    if(st.charAt(2)=='1'){
               // st.replace(1,2,"13");
                st.setCharAt(0, '1');
                st.setCharAt(1, '7');
         }else if(st.charAt(0)=='0' && st.charAt(1)=='6' &&st.charAt(8)=='P' ){
        //    if(st.charAt(2)=='1'){
               // st.replace(1,2,"13");
                st.setCharAt(0, '1');
                st.setCharAt(1, '8');
         }else if(st.charAt(0)=='0' && st.charAt(1)=='7' &&st.charAt(8)=='P' ){
        //    if(st.charAt(2)=='1'){
               // st.replace(1,2,"13");
                st.setCharAt(0, '1');
                st.setCharAt(1, '9');
         }else if(st.charAt(0)=='0' && st.charAt(1)=='8' &&st.charAt(8)=='P' ){
        //    if(st.charAt(2)=='1'){
               // st.replace(1,2,"13");
                st.setCharAt(0, '2');
                st.setCharAt(1, '0');
         }else if(st.charAt(0)=='0' && st.charAt(1)=='9' &&st.charAt(8)=='P' ){
        //    if(st.charAt(2)=='1'){
               // st.replace(1,2,"13");
                st.setCharAt(0, '2');
                st.setCharAt(1, '1');
         }else if(st.charAt(0)=='1' && st.charAt(1)=='0' &&st.charAt(8)=='P' ){
        //    if(st.charAt(2)=='1'){
               // st.replace(1,2,"13");
                st.setCharAt(0, '2');
                st.setCharAt(1, '2');
         }else if(st.charAt(0)=='1' && st.charAt(1)=='1' &&st.charAt(8)=='P' ){
        //    if(st.charAt(2)=='1'){
               // st.replace(1,2,"13");
                st.setCharAt(0, '2');
                st.setCharAt(1, '3');
         }else if(st.charAt(0)=='1' && st.charAt(1)=='2' &&st.charAt(8)=='A'  ){
        //    if(st.charAt(2)=='1'){
               // st.replace(1,2,"13");
                st.setCharAt(0, '0');
                st.setCharAt(1, '0');
         }else if(st.charAt(0)=='1' && st.charAt(1)=='2' &&st.charAt(8)=='P'  ){
                st.setCharAt(0, '1');
                st.setCharAt(1, '2');
         }
         if(st.charAt(8)=='P'){
             st.setCharAt(8,' ');

         }else if(st.charAt(8)== 'A'){
             st.setCharAt(8,' ');
         }
         if(st.charAt(9)=='M'){
             st.setCharAt(9,' ');
         }
   }
   String result=st.toString();
   return result;
}

You asked about efficiency, which I am not an expert in. However, if you are going to share your code here, it would be nice if you could adapt it to the Java code style conventions.
In short: you should use PascalCase for your class names, so…

  • Main.java instead of main.java
  • Time.java instead of time.java
  • Window.java instead of window.java

Also, using single-letter names for your parameters is discouraged (borderline in the case of the fairly obvious int h and int m, bad in the case of String t). Why not hours, minutes, and halfOfDaySuffix? I’m sure you could find an even better term for the latter with a little research.

If you haven’t already, make sure you organize your code into one or more package(s), e.g. put package com.jackwilsdon.TimeConversion; at the beginning of your files. This helps avoid name clashing problems (for instance with java.sql.Time).

In regard to to24h(): Never compare two Strings with the == (reference equals) operator in Java. This will only work in a narrow range of scenarios, read the full explanation on StackOverflow. You need to use the String.equals method instead.

But while we are at it, you shouldn’t be using a String to represent AM/PM anyway — it will stop working if you pass in the wrong string, for instance pm instead of PM by mistake. Instead, restrict the possible values by creating an Enum:

public enum DayHalf {
    AM,
    PM
}

Then (in Window), you can change tAMPM‘s type from String to DayHalf — the following line will stop working:

tAMPM = (String)combo.getSelectedItem();

So you need to use combo = new JComboBox(DayHalf.values()); instead of combo = new JComboBox(times); and change the above line to

tAMPM = (DayHalf)combo.getSelectedItem();

If you are passing in AM or PM, hours above 12 are not acceptable — neither are minutes above 59! Hence, your conditions are erroneous; also, silently failing by setting the fields to 0 isn’t a robust solution. You should throw an IllegalArgumentException if the values are out of range.

Your updated setTime method would look something like this:

public void setTime(int hours, int minutes, DayHalf halfOfDaySuffix) {
    if (hours < 0 || hours > 12 || minutes < 0 || minutes > 59)
        throw new IllegalArgumentException("hours or minutes out of allowed range!");
    hour = hours;
    minute = minutes;
    dayHalf = halfOfDaySuffix;
}

Regarding your JFrame (Window.java, should probably be called TimeConversionWindow.java), you should adjust the obviously copied-and-pasted error message:

else if (tMinutes > 60) {
    output.setText("Please enter a 12 hour number!");
}

to «Please enter less than 60 minutes!» or similar. Note that your condition (tMinutes > 60) is incorrect once again and should be changed to > 59.

A couple of other adjustments will be required, but they are easy to figure out. I’d argue that performance is nearly irrelevant in this scenario, read up on bottlenecks.

You asked about efficiency, which I am not an expert in. However, if you are going to share your code here, it would be nice if you could adapt it to the Java code style conventions.
In short: you should use PascalCase for your class names, so…

  • Main.java instead of main.java
  • Time.java instead of time.java
  • Window.java instead of window.java

Also, using single-letter names for your parameters is discouraged (borderline in the case of the fairly obvious int h and int m, bad in the case of String t). Why not hours, minutes, and halfOfDaySuffix? I’m sure you could find an even better term for the latter with a little research.

If you haven’t already, make sure you organize your code into one or more package(s), e.g. put package com.jackwilsdon.TimeConversion; at the beginning of your files. This helps avoid name clashing problems (for instance with java.sql.Time).

In regard to to24h(): Never compare two Strings with the == (reference equals) operator in Java. This will only work in a narrow range of scenarios, read the full explanation on StackOverflow. You need to use the String.equals method instead.

But while we are at it, you shouldn’t be using a String to represent AM/PM anyway — it will stop working if you pass in the wrong string, for instance pm instead of PM by mistake. Instead, restrict the possible values by creating an Enum:

public enum DayHalf {
    AM,
    PM
}

Then (in Window), you can change tAMPM‘s type from String to DayHalf — the following line will stop working:

tAMPM = (String)combo.getSelectedItem();

So you need to use combo = new JComboBox(DayHalf.values()); instead of combo = new JComboBox(times); and change the above line to

tAMPM = (DayHalf)combo.getSelectedItem();

If you are passing in AM or PM, hours above 12 are not acceptable — neither are minutes above 59! Hence, your conditions are erroneous; also, silently failing by setting the fields to 0 isn’t a robust solution. You should throw an IllegalArgumentException if the values are out of range.

Your updated setTime method would look something like this:

public void setTime(int hours, int minutes, DayHalf halfOfDaySuffix) {
    if (hours < 0 || hours > 12 || minutes < 0 || minutes > 59)
        throw new IllegalArgumentException("hours or minutes out of allowed range!");
    hour = hours;
    minute = minutes;
    dayHalf = halfOfDaySuffix;
}

Regarding your JFrame (Window.java, should probably be called TimeConversionWindow.java), you should adjust the obviously copied-and-pasted error message:

else if (tMinutes > 60) {
    output.setText("Please enter a 12 hour number!");
}

to «Please enter less than 60 minutes!» or similar. Note that your condition (tMinutes > 60) is incorrect once again and should be changed to > 59.

A couple of other adjustments will be required, but they are easy to figure out. I’d argue that performance is nearly irrelevant in this scenario, read up on bottlenecks.

In this tutorial, we are going to learn Time conversion in Java (i.e) how we can convert 12-hour time notation to 24-hour time notation. In simple words given a time in 12-hour AM/PM format, we’ll convert it to military (24-hour) time. So what is 24-hour time notation?

A 24-hour clock is a way of telling the time in which time is divided into 24 hours and is numbered from 0 to 24. It does not use a.m. or p.m. It is also called as military time, continental time or railway time.

Note: Midnight is 12:00:00 AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00 PM on a 12-hour clock, and 12:00:00 on a 24-hour clock.

Code for implementing Time conversion in Java

import java.util.*;
class time
{
  public static void main(String[]args) {      

    Scanner scan = new Scanner(System.in);
    String time = scan.next();

    //splitting the string in parts when we encounter ":" in the string
    String tArr[] = time.split(":");
    String AmPm = tArr[2].substring(2,4);
    int hh,mm,ss;

    //converting the strings to integers
    hh = Integer.parseInt(tArr[0]);
    mm = Integer.parseInt(tArr[1]);
    ss = Integer.parseInt(tArr[2].substring(0,2));
        
    String checkPM = "PM",checkAM ="AM";
       
    if(AmPm.equals(checkAM) && hh==12)
    {
      	hh=0;
    }
    else if(AmPm.equals(checkPM)&& hh<12)
    {
      	hh+=12;
    }
        
    System.out.printf("%02d:%02d:%02d",hh,mm,ss);

  }
}

Output:

12:00:00AM
00:00:00
07:05:45PM
19:05:45
12:45:54PM
12:45:54

Explanation

  1. We scan the input string and split the string into individual numbers when encountering a colon (:) using the split function.
  2. Next, we convert the number strings to integers using the Integer.parseInt() function.
  3.  Then we check the meridian using equals function and perform the respective operations.

Note: %02d means: 2 digits and left padding with zeros.
Example 1: If the number is 7 then %02d formats it as 07.
Example 2: If the number is 54 then %02d formats it as 54.

Hope you’ve understood the code 🙂
Any questions feel free to drop in your comments.

You can also check other posts:

  • Java Program to find out a Kaprekar Number
  • Implementing Caesar Cipher in Java

Sometimes we need to convert the milliseconds into days or hours or minutes or seconds, so in this post we will see how to convert milliseconds into days, hours, minutes, seconds in Java.

Basically when you want to check the exact time taken to execute a program then you may need to calculate the time. So in this case you get the start time in milliseconds and end time in milliseconds and you want to check how much time that program took to execute. Therefore you would like to convert the milliseconds into minutes and seconds to make it more readable format because millisecond unit may not be so understandable quickly.

Convert Milliseconds into Days, Hours, Minutes, Seconds in Java

Lets see the below example, it will provide you better idea to convert the milliseconds into days or hours or minutes or seconds.

Formula to convert Milliseconds into Days, Hours, Minutes, Seconds in Java:
seconds = MilliSeconds / 1000;
minutes = seconds / 60;
hours = minutes / 60;
days = hours / 24;
  

import java.util.concurrent.TimeUnit;

public class MillisToDayHrMinSec {
 
 public static void main(String[] args) {
  final long milliseconds = 5478965412358l;
  final long day = TimeUnit.MILLISECONDS.toDays(milliseconds);
  
  final long hours = TimeUnit.MILLISECONDS.toHours(milliseconds)
    - TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(milliseconds));
  
  final long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds)
    - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(milliseconds));
  
  final long seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds)
    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milliseconds));
  
  final long ms = TimeUnit.MILLISECONDS.toMillis(milliseconds)
    - TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(milliseconds));
  
  System.out.println("milliseconds :-" + milliseconds);
  System.out.println(String.format("%d Days %d Hours %d Minutes %d Seconds %d Milliseconds", day, hours, minutes, seconds, ms));
 }

}

Output :
———————
milliseconds :-5478965412358
63413 Days 22 Hours 50 Minutes 12 Seconds 358 Milliseconds

Hope you like this simple example for time conversion, where we are converting milliseconds into days or hours or minutes or seconds. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

WWH

4 / 4 / 2

Регистрация: 23.12.2016

Сообщений: 124

1

Перевод секунд в минуты и часы

11.01.2018, 19:06. Показов 21460. Ответов 4

Метки нет (Все метки)


На вход подается количество секунд. Задача: перевести секунды в часы и минуты. Аутпут должен иметь вид: 03:59:15.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class HumanReadableTime {
  public static String makeReadable(int seconds) {
    int SS = 0; int MM = 0; int HH = 0;
        
    HH = seconds / 3600;
    MM = (seconds - HH * 3600) / 60;
    SS = seconds - HH * 3600 - MM * 60; 
 
    StringBuilder time = time.append(HH).append(":").append(MM).append(":").append(SS);
    if(HH < 10) time.insert(0, "0");
    if(SS < 10) time.append("0");
 
    return time.toString();
  }
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

11.01.2018, 19:06

4

Эксперт Java

3638 / 2970 / 918

Регистрация: 05.07.2013

Сообщений: 14,220

11.01.2018, 19:27

2

че надо то?



0



_ViPeR_

611 / 485 / 175

Регистрация: 02.03.2010

Сообщений: 1,230

12.01.2018, 06:42

3

Че за жескач?
Почему нельзя:

Java
1
new SimpleDateFormat("HH:mm:ss").format(new Date(TimeUnit.SECONDS.toMillis(seconds)))



0



Хм

211 / 183 / 68

Регистрация: 21.10.2016

Сообщений: 410

12.01.2018, 08:54

4

Если в пределах суток, то можно так:

Java
1
2
3
4
5
6
7
8
import java.time.*;
 
class GetTime {
 
    public static void main(String[] args) {
        System.out.println(LocalTime.ofSecondOfDay(86399));
    }
}
Bash
1
2
3
const@mate ~/progs $ javac GetTime.java
const@mate ~/progs $ java GetTime
23:59:59



1



easybudda

Модератор

Эксперт PythonЭксперт JavaЭксперт CЭксперт С++

11682 / 7192 / 1707

Регистрация: 25.07.2009

Сообщений: 13,181

12.01.2018, 16:18

5

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.Scanner;
 
public class HumanReadableTime {
    public static String makeReadable(int sec) {
        return String.format("%d:%02d:%02d", sec / 3600, sec % 3600 / 60, sec % 60);
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        while ( true ) {
            System.out.print("Seconds: ");
            if ( ! scanner.hasNextInt() )
                break;
            int sec = scanner.nextInt();
            if ( sec < 0 )
                break;
            System.out.println("Human readable: " + makeReadable(sec));
        }
        
        scanner.close();
    }
}



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

12.01.2018, 16:18

5

Последнее обновление 09 июля 2019 06:32:20 (UTC / GMT +8 часов)

script1adsense2code

script1adsense3code

Java Basic: упражнение 55 с решением

Напишите Java-программу для преобразования секунд в часы, минуты и секунды.

Иллюстрированная презентация:


Пример данных:
Входные секунды: 86399
23:59:59

Пример решения:

Java-код:

import java.util.*;
 public class Exercise55 {
 public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Input seconds: ");
		int seconds = in.nextInt(); 
        int p1 = seconds % 60;
        int p2 = seconds / 60;
        int p3 = p2 % 60;
        p2 = p2 / 60;
        System.out.print( p2 + ":" + p3 + ":" + p1);
		System.out.print("n");
    }    
 }

Пример вывода:

 Входные секунды: 86399                                                   
23:59:59

Иллюстрированная презентация:

«Иллюстрированные

Блоксхема:

«Блок-схема:

Редактор кода Java:

Внесите свой код и комментарии через Disqus.

Предыдущий: Напишите Java-программу, которая принимает три целых числа от пользователя и возвращает true, если два или более из них (целые числа) имеют одинаковую самую правую цифру.
Далее: Напишите программу на Java, чтобы найти число целых чисел в диапазоне двух указанных чисел, которые делятся на другое число.

Понравилась статья? Поделить с друзьями:
  • Как написать конвертер валют на python
  • Как написать конверт бабушке
  • Как написать комфортное письмо
  • Как написать кому юлии или юлие как правильно
  • Как написать кому то на почту