java 我获得单位为毫秒的当前时间,如何转化成年月日小时分格式?

Python029

java 我获得单位为毫秒的当前时间,如何转化成年月日小时分格式?,第1张

分类: 电脑/网络 >>程序设计 >>其他编程语言

问题描述:

得到一个毫秒时间,是1970年1月1日0:00至今的毫秒时间,怎么转换成通常格式

解析:

import java.util.*

import java.text.SimpleDateFormat

public class test

{

public static void main (String args[])

{

Date d = new Date()

long longtime = d.getTime()

System.out.println(longtime)

你获得的是上面的long型数据吧

String time = d.toLocaleString()

你可以简单的得到本地化时间,本来就是String类型的就不用转换了

System.out.println(time)

也可以自己用SimpleDateFormat这个函数把它变成自己想要的格式,注意需要import java.text.SimpleDateFormat

SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")

System.out.println(sdf.format(longtime))

}

}

首先获取当前时间:

java.util.Date nowdate = new java.util.Date()

2/2

然后如果你想时间的格式和你想用的时间格式一致 那么就要格式化时间了SimpleDateFormat 的包在java.text包下SimpleDateFormat

sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") //年月日 时分

String t = sdf.parse(nowdate);