如何将整数(例如 19000101 )转换为 java.util.Date?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25458832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:27:26  来源:igfitidea点击:

How can I convert an Integer (e.g 19000101 ) to java.util.Date?

javadateintegerdata-conversion

提问by sbanerjee

Here's my code:

这是我的代码:

Integer value = 19000101 ;         

How can I convert the above Integer represented in YYYYMMDDformat to YYYY-MM-DDformat in java.util.Date?

如何将上述YYYYMMDDYYYY-MM-DD格式表示的整数转换为格式 java.util.Date

采纳答案by Adi

First you have to parse your format into date object using formatter specified

首先,您必须使用指定的格式化程序将格式解析为日期对象

Integer value = 19000101;
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyyMMdd");
Date date = originalFormat.parse(value.toString());

Remember that Date has no format. It just represents specific instance in time in milliseconds starting from 1970-01-01. But if you want to format that date to your expected format, you can use another formatter.

请记住,日期没有格式。它仅代表从 1970-01-01 开始的以毫秒为单位的特定时间实例。但是如果您想将该日期格式化为您期望的格式,您可以使用另一个格式化程序。

SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd");
String formatedDate = newFormat.format(date);

Now your formatedDateString should contain string that represent date in format yyyy-MM-dd

现在你的formatedDateString 应该包含以格式表示日期的字符串yyyy-MM-dd

回答by Rahul Tripathi

Try this:

尝试这个:

String myDate= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                          .format(new Date(19000101 * 1000L));

Assuming it is the time since 1/1/1970

假设它是自 1/1/1970 以来的时间

EDIT:-

编辑:-

If you want to convert from YYYYMMDD to YYYY-MM-DD format

如果要将 YYYYMMDD 格式转换为 YYYY-MM-DD 格式

Date dt = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH).parse(String.ValueOf(19000101));

回答by Alexis King

It seems to me that you don't really have a numberrepresenting your date, you have a string of three numbers: year, month, and day. You can extract those values with some simple arithmetic.

在我看来,您实际上并没有代表日期的数字,而是一串三个数字:年、月和日。您可以使用一些简单的算术提取这些值。

Integer value = 19000101;
int year = value / 10000;
int month = (value % 10000) / 100;
int day = value % 100;
Date date = new GregorianCalendar(year, month, day).getTime();