How to convert a long to a Date with “dd/MM/yyyy” format [duplicate]

最后都变了- 提交于 2019-12-14 03:29:47

问题


I have a variable of type Long.
Long longDate = 20180201110400

It represents this: 2018/02/01 11:04:00

I want to convert the format and variable type like below:

Format should be "dd/MM/yyyy" and type should be Date. How can I do that?


回答1:


You can covert the long to a Date object first then you can further convert it to your desired format. Below is the code sample.

Long longDate = 20180201110400L;

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

Date date  = dateFormat.parse(longDate.toString());

System.out.println("Date : "+date);

SimpleDateFormat dateFormatNew = new SimpleDateFormat("dd/MM/yyyy");

String formattedDate = dateFormatNew.format(date);

System.out.println("Formatted date : "+formattedDate);



回答2:


cast Long to Date:

Long longDate = 20180201110400L;
String dateAsString = String.valueOf(longDate);
Date date = new SimpleDateFormat("yyyyMMddHHmmss").parse(dateAsString);

cast Date to String with "dd/MM/yyyy" format:

String formattedDate = new SimpleDateFormat("dd/MM/yyyy").format(date);



回答3:


To convert in any standard date format, we can use SimpleDateFormat class. See the below snippet

Long longDate = new Date().getTime();   
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String formatedDate = dateFormat.format(longDate);

System.out.println(formatedDate);

Output : 01/02/2018



来源:https://stackoverflow.com/questions/48558248/how-to-convert-a-long-to-a-date-with-dd-mm-yyyy-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!