如何在Android中将Date转换为特定格式? [英] How to convert Date to a particular format in android?
问题描述
"2016年3月10日,下午6:30:00",这是我的约会日期,我想将其转换为"2016年3月10日".我可以在Android中使用SimpleDateFormat吗?我没有确切的模式来转换它.请先帮助并谢谢
"Mar 10, 2016 6:30:00 PM" This is my date and I want to convert this into "10 Mar 2016". Can I use SimpleDateFormat in android. I am not getting the exact pattern to convert it. Please help and thanks in advance
String date="Mar 10, 2016 6:30:00 PM";
SimpleDateFormat spf=new SimpleDateFormat("Some Pattern for above date");
Date newDate=spf.format(date);
spf= new SimpleDateFormat("dd MMM yyyy");
String date = spf.format(newDate);
此步骤有效吗?如果是,有人可以给我这样的格式吗?预先感谢.
Will this steps work? If yes, can someone please give me a pattern of that format? Thanks in advance.
推荐答案
这是您应该使用的修改后的代码:
This is modified code that you should use:
String date="Mar 10, 2016 6:30:00 PM";
SimpleDateFormat spf=new SimpleDateFormat("MMM dd, yyyy hh:mm:ss aaa");
Date newDate=spf.parse(date);
spf= new SimpleDateFormat("dd MMM yyyy");
date = spf.format(newDate);
System.out.println(date);
使用hh
数小时以获取正确的时间.
Use hh
for hours in order to get correct time.
Java 8及更高版本
Java 8引入了用于时间操作的新类,因此在这种情况下,请使用以下代码:
Java 8 introduced new classes for time manipulation, so use following code in such cases:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy h:mm:ss a");
LocalDateTime dateTime = LocalDateTime.parse(date, formatter);
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("dd MMM yyyy");
System.out.println(dateTime.format(formatter2));
使用h
表示小时格式,因为在这种情况下,小时只有一位数字.
Use h
for hour format, since in this case hour has only one digit.
这篇关于如何在Android中将Date转换为特定格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!