我正在研究Java。我有一个日期,例如:20120328。年份是2012,月份是03,日期是28。我想将其转换为yyyy-MM-dd
格式。我已经尝试过了,但是没有用。怎么做?
首先,您使用类似的子字符串创建格式
String myDate = "20120328";
String myConvertedDate = myDate.substring(0,4) + "-" + myDate.substring(5,6) + "-" + myDate.substring(7);
此生成的日期为2012-03-28
然后根据需要使用简单的日期格式将其转换为日期。
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
String ourformat = formatter.format(date.getTime());
如果您不想使用“ MM / dd / yyyy”,则只需更改SimpleDateFormat中的格式
找到一些例子here。
DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
Date date = (Date)formatter.parse("01/29/02");
看看here。您将需要使用SimpleDateFormat
类。
您可以将其用于日期格式
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);