如何在android studio中将日期格式从14-feb-2019更改为14-02-2019,实际上我正在选择系统日期,但我想在Android Studio中更改2月到月号,这是我的代码片段:
eddate = (EditText) findViewById(R.id.editdate);
edtime = (EditText) findViewById(R.id.editime);
eddate.setFocusable(false);
Calendar calendar = Calendar.getInstance();
String currentDate = DateFormat.getDateInstance().format(calendar.getTime());
String[] arr=currentDate.split(" ");
String date=arr[0]+"-"+arr[1]+"-"+arr[2];
// Toast.makeText(this, ""+date, Toast.LENGTH_SHORT).show();
eddate.setText(date);
您正在使用区域设置的内置日期格式,这是一个好主意。这很简单,你正在利用有人知道这种格式的样子,你的代码很适合国际化。执行此操作时,您可以选择所需格式的长短。你可能做了类似于以下的事情:
ZoneId zone = ZoneId.of("Asia/Karachi");
Locale pakistan = Locale.forLanguageTag("en-PK");
DateTimeFormatter mediumFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(pakistan);
LocalDate today = LocalDate.now(zone);
System.out.println(today.format(mediumFormatter));
15月 - 2019
在我的片段中,我指定了一种中等格式。我认为你最好的选择是使用短格式:
DateTimeFormatter shortFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT).withLocale(pakistan);
System.out.println(today.format(shortFormatter));
15/02/2019
这使用斜杠而不是连字符。我相信这就是你文化中的人们通常希望看到以短格式书写日期的方式。并且您已经保存了字符串操作或其他手动格式。
在我的片段中,我使用的是java.time,即现代Java日期和时间API。 Calendar
和DateFormat
已经过时了,后者尤其出了名的麻烦。现代API可以更好地使用。
免责声明:我已经在我的Java 10上运行了片段。在Android上的输出可能会有所不同。我不会太担心。在所有情况下,都谨慎选择了内置的本地化格式。
是的,java.time适用于较旧和较新的Android设备。它至少需要Java 6。
org.threeten.bp
导入子包的日期和时间类。java.time
首次被描述。java.time
的后端到Java 6和7(JST-310的ThreeTen)。String dateFormat= "dd-MM-yyyy";
Date date = calendar.getTime();
String dateText= new SimpleDateFormat(dateFormat).format(date);
试试这会对你有所帮助
public class Test {
public static void main(String[] args) {
String parseddate = parseDateToddMMyyyy("14-feb-2019");
System.out.println(parseddate);
}
public static String parseDateToddMMyyyy(String time) {
String outputPattern = "dd-MM-yyyy";
String inputPattern= "dd-MMM-yyyy";
SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern);
SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
Date date = null;
String str = null;
try {
date = inputFormat.parse(time);
str = outputFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return str;
}
}