将毫秒转换为分和秒的Java程序
使用并发包中的 toMinutes() 和 toSeconds() 等方法,在Java中将毫秒转换为分钟和秒。
毫秒:
1 millisecond = 0.001 second or (1/1000) seconds
秒:
1 second = 1000 millisecond
1 second = (1/60) minutes
分钟:
1 minute = 60000 milliseconds
1 minute = 60 seconds
1 minute = (1/60)hour
例子:
Input : Milliseconds = 400000
Output: 6 minutes and 40 seconds
Input : Milliseconds = 5400000
Output: 90 minutes and 0 seconds
算法:
- 以毫秒为单位获取输入。
- 使用公式将毫秒转换为分钟:分钟 = (毫秒/1000)/60)。
- 使用公式将毫秒转换为秒:秒 = (毫秒/1000)%60)。
- 从毫秒到分秒的打印输出
解决方法:将毫秒转换为分和秒的Java程序。
- 只需在Java中使用基本输入/输出。
- 在Java中使用方法。
1. 将毫秒转换为分和秒的程序
Java
// Java Program to Convert Milliseconds
// to Minutes and Seconds
import java.io.*;
class GFG {
public static void main(String[] args)
{
// Take Input in Long otherwise
// overflow occur for some inputs.
long milliseconds = 3500000;
// formula for conversion for
// milliseconds to minutes.
long minutes = (milliseconds / 1000) / 60;
// formula for conversion for
// milliseconds to seconds
long seconds = (milliseconds / 1000) % 60;
// Print the output
System.out.println(milliseconds + " Milliseconds = "
+ minutes + " minutes and "
+ seconds + " seconds.");
}
}
Java
// Java Program to Convert Milliseconds
// to Minutes and Seconds
import java.io.*;
import java.util.concurrent.TimeUnit;
class GFG {
public static void main(String[] args)
{
long milliseconds = 3500000;
// This method uses this formula :minutes =
// (milliseconds / 1000) / 60;
long minutes
= TimeUnit.MILLISECONDS.toMinutes(milliseconds);
// This method uses this formula seconds =
// (milliseconds / 1000);
long seconds
= (TimeUnit.MILLISECONDS.toSeconds(milliseconds)
% 60);
// Print the answer
System.out.format(milliseconds + " Milliseconds = "
+ minutes + " minutes and "
+ seconds + " seconds");
}
}
输出
3500000 Milliseconds = 58 minutes and 20 seconds.
2. 使用方法将毫秒转换为分和秒的程序。
Java
// Java Program to Convert Milliseconds
// to Minutes and Seconds
import java.io.*;
import java.util.concurrent.TimeUnit;
class GFG {
public static void main(String[] args)
{
long milliseconds = 3500000;
// This method uses this formula :minutes =
// (milliseconds / 1000) / 60;
long minutes
= TimeUnit.MILLISECONDS.toMinutes(milliseconds);
// This method uses this formula seconds =
// (milliseconds / 1000);
long seconds
= (TimeUnit.MILLISECONDS.toSeconds(milliseconds)
% 60);
// Print the answer
System.out.format(milliseconds + " Milliseconds = "
+ minutes + " minutes and "
+ seconds + " seconds");
}
}
输出
3500000 Milliseconds = 58 minutes and 20 seconds