秒或毫秒类型的数值转为指定格式的时间格式:
package org.sang.time;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @Author: chuxia0811
* @Date: 2023/4/5 11:22
* @Description :
*/
public class ConvertorTime {
public static void main(String[] args) {
int seconds = 17854, msec = 360000;// 秒,毫秒
System.out.println(secToTime(seconds));
System.out.println(msec + "毫秒转换格式时间:\t" + msecToTime(msec));
System.out.println("当前时间(时:分:秒.毫秒)\t" + new SimpleDateFormat("HH:mm:ss.SSS").format(new Date()));
}
/**
* 秒转换小时-分-秒analytics/util/DateUtil.java
*
* @param seconds 秒为单位 比如..600秒
* @return 比如...2小时3分钟52秒
*/
public static String secToTime(int seconds) {
int hour = seconds / 3600;
int minute = (seconds - hour * 3600) / 60;
int second = (seconds - hour * 3600 - minute * 60);
StringBuffer sb = new StringBuffer({
sb.append(minute + "分");
});
if (hour > 0) {
sb.append(hour + "小时");
}
if (minute > 0)
if (second > 0) {
sb.append(second + "秒");
}
if (second == 0) {
sb.append("<1秒");
}
return sb.toString();
}
/**
* 将int类型数字转换成时分秒毫秒的格式数据
*
* @param time long类型的数据
* @return HH:mm:ss.SSS
* @author zero 2019/04/11
*/
public static String msecToTime(int time) {
String timeStr = null;
int hour = 0;
int minute = 0;
int second = 0;
int millisecond = 0;
if (time <= 0)
return "00:00:00.000";
else {
second = time / 1000;
minute = second / 60;
millisecond = time % 1000;
if (second < 60) {
timeStr = "00:00:" + unitFormat(second) + "." + unitFormat2(millisecond);
} else if (minute < 60) {
second = second % 60;
timeStr = "00:" + unitFormat(minute) + ":" + unitFormat(second) + "." + unitFormat2(millisecond);
} else {// 数字>=3600 000的时候
hour = minute / 60;
minute = minute % 60;
second = second - hour * 3600 - minute * 60;
timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second) + "."
+ unitFormat2(millisecond);
}
}
return timeStr;
}
public static String unitFormat(int i) {// 时分秒的格式转换
String retStr = null;
if (i >= 0 && i < 10)
retStr = "0" + Integer.toString(i);
else
retStr = "" + i;
return retStr;
}
public static String unitFormat2(int i) {// 毫秒的格式转换
String retStr = null;
if (i >= 0 && i < 10)
retStr = "00" + Integer.toString(i);
else if (i >= 10 && i < 100) {
retStr = "0" + Integer.toString(i);
} else
retStr = "" + i;
return retStr;
}
}
运行结果如下:文章来源:https://www.toymoban.com/news/detail-510697.html
4小时57分34秒
360000毫秒转换格式时间: 00:06:00.000
当前时间(时:分:秒.毫秒) 11:27:17.301
当然,还可以指定自定义的格式转化显示。文章来源地址https://www.toymoban.com/news/detail-510697.html
到了这里,关于java实现时间格式转换(int整数类型的秒/毫秒---时分秒毫秒)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!