JAVA获取当前时间和将已有的long类型时间转换为年月日时分秒格式

代码如下:

public class DateUtil {

	/**
	 * 根据格式获取当前格式化时间
	 * @param format 格式化方式,基础格式为yyyy-MM-dd HH:mm:ss
	 * @return 当前时间
	 */
	public static String getCurrentTimeByFormat(String format) 
	{
		SimpleDateFormat df = new SimpleDateFormat(format);
		return df.format(new Date());
	}
	
	/**
	 * 格式化时间
	 * @param format 格式化格式,基础格式为yyyy-MM-dd HH:mm:ss
	 * @param currentTime
	 * @return
	 */
	public static String formatTime(String format, long time) 
	{
		SimpleDateFormat df = new SimpleDateFormat(format);
		return df.format(new Date(time));
	}
}

获取当前时间的年月日时分秒格式字符串:

首先将当前时间转换为十二小时制的年/月/日 时:分:秒 格式,输入的格式为yyyy/MM/dd hh:mm:ss

public static void main(String[] args) {
		String time = DateUtil.getCurrentTimeByFormat("yyyy/MM/dd hh:mm:ss");
		System.out.println(time);
	}

结果为:2018/09/19 11:08:26

换位二十四小时制,则输入参数yyyy/MM/dd HH:mm:ss:

public static void main(String[] args) {
		String time = DateUtil.getCurrentTimeByFormat("yyyy/MM/dd HH:mm:ss");
		System.out.println(time);
	}

执行输出结果为2018/09/19 23:09:51;

如只想要年月日,则入参为yyyy/MM/dd

public static void main(String[] args) {
		String time = DateUtil.getCurrentTimeByFormat("yyyy/MM/dd");
		System.out.println(time);
	}

输出结果为2018/09/19;

同理只要时分秒则入参为HH:mm:ss,可以根据需要灵活配置,左斜杠/可以换为-等符号或者干脆不要,时分秒中的:同理;

转换long类型时间

测试:

public static void main(String[] args) {
		String time = DateUtil.formatTime("yyyy-MM-dd HH:mm:ss", 1527320060036L);
		System.out.println(time);
	}

结果:

2018-05-26 15:34:20

结果正常,format参数一样可以自己定义;

猜你喜欢

转载自blog.csdn.net/df0128/article/details/82779926