数字日期格式

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

如何在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);
java android date-formatting
3个回答
1
投票

您正在使用区域设置的内置日期格式,这是一个好主意。这很简单,你正在利用有人知道这种格式的样子,你的代码很适合国际化。执行此操作时,您可以选择所需格式的长短。你可能做了类似于以下的事情:

    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。 CalendarDateFormat已经过时了,后者尤其出了名的麻烦。现代API可以更好地使用。

免责声明:我已经在我的Java 10上运行了片段。在Android上的输出可能会有所不同。我不会太担心。在所有情况下,都谨慎选择了内置的本地化格式。

问题:我可以在Android上使用java.time吗?

是的,java.time适用于较旧和较新的Android设备。它至少需要Java 6。

  • 在Java 8及更高版本和更新的Android设备上(来自API级别26),现代API内置。
  • 在Java 6和7中获取ThreeTen Backport,现代类的后端(JST 310的ThreeTen;请参见底部的链接)。
  • 在(较旧的)Android上使用Android版的ThreeTen Backport。它被称为ThreeTenABP。并确保从org.threeten.bp导入子包的日期和时间类。

链接


0
投票
String dateFormat= "dd-MM-yyyy";
Date date = calendar.getTime();
String dateText= new SimpleDateFormat(dateFormat).format(date);

0
投票

试试这会对你有所帮助

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;
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.