将日期转换为特定格式

问题描述 投票:0回答:5

我正在研究Java。我有一个日期,例如:20120328。年份是2012,月份是03,日期是28。我想将其转换为yyyy-MM-dd格式。我已经尝试过了,但是没有用。怎么做?

java date simpledateformat
5个回答
0
投票

首先,您使用类似的子字符串创建格式

String myDate = "20120328";
String myConvertedDate = myDate.substring(0,4) + "-" + myDate.substring(5,6) + "-" + myDate.substring(7);

此生成的日期为2012-03-28

然后根据需要使用简单的日期格式将其转换为日期。


5
投票
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
String ourformat = formatter.format(date.getTime());

如果您不想使用“ MM / dd / yyyy”,则只需更改SimpleDateFormat中的格式


2
投票

找到一些例子here

  DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
  Date date = (Date)formatter.parse("01/29/02");

1
投票

看看here。您将需要使用SimpleDateFormat类。


0
投票

您可以将其用于日期格式

SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
String ourformat = formatter.format(date.getTime());

还有这个用于获取时间戳记的>]

    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
    Timestamp timestamp =timestamp=new Timestamp(System.currentTimeMillis());
    String ourformat = formatter.format(timestamp);
© www.soinside.com 2019 - 2024. All rights reserved.