数字日期格式

时间:2019-02-14 12:43:59

标签: java android date-formatting

如何在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);

3 个答案:

答案 0 :(得分: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));
  

2019年2月15日

在我的代码段中,我指定了一种中等格式。我认为您最好的选择是使用短格式:

    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反向端口,这是现代类的反向端口(JSR 310的ThreeTen;请参见底部的链接)。
  • 在(较旧的)Android上,使用Android版本的ThreeTen Backport。叫做ThreeTenABP。并确保您使用子包从org.threeten.bp导入日期和时间类。

链接

答案 1 :(得分:0)

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

答案 2 :(得分: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;
    }

}
相关问题