在有年、月、日、时、分的情况下,如何根据设备配置的日期和时间正确格式化?


当前回答

The other answers are generally correct. I should like to contribute the modern answer. The classes Date, DateFormat and SimpleDateFormat used in most of the other answers, are long outdated and have caused trouble for many programmers over many years. Today we have so much better in java.time, AKA JSR-310, the modern Java date & time API. Can you use this on Android yet? Most certainly! The modern classes have been backported to Android in the ThreeTenABP project. See this question: How to use ThreeTenABP in Android Project for all the details.

这段代码应该让你开始:

    int year = 2017, month = 9, day = 28, hour = 22, minute = 45;
    LocalDateTime dateTime = LocalDateTime.of(year, month, day, hour, minute);
    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
    System.out.println(dateTime.format(formatter));

当我将电脑的首选语言设置为美式英语或英式英语时,打印如下:

Sep 28, 2017 10:45:00 PM

当我把它设置为丹麦语时,我得到:

28-09-2017 22:45:00

所以它符合构型。不过,我不确定它具体跟踪了你设备的日期和时间设置的哪些细节,而且这可能因手机而异。

其他回答

在我看来,android.text.format.DateFormat. getdateformat (context)让我感到困惑,因为这个方法返回java.text.DateFormat而不是android.text.format.DateFormat - -"。

因此,我使用下面的片段代码以我的格式获取当前日期/时间。

android.text.format.DateFormat df = new android.text.format.DateFormat();
df.format("yyyy-MM-dd hh:mm:ss a", new java.util.Date());

or

android.text.format.DateFormat.format("yyyy-MM-dd hh:mm:ss a", new java.util.Date());

此外,您还可以使用其他格式。遵循DateFormat。

这是最简单的方法:

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a", Locale.US);

    String time = df.format(new Date());

如果你在寻找模式,检查这个 https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

现在已经太迟了,但它可能对某人有所帮助

DateFormat.format(format, timeInMillis);

这里是你需要的格式

"HH:mm"返回15:30

Date to Locale日期字符串:

Date date = new Date();
String stringDate = DateFormat.getDateTimeInstance().format(date);

选项:

   DateFormat.getDateInstance() 

- > 1969年12月31日

   DateFormat.getDateTimeInstance() 

-> 1969年12月31日下午4:00:00

   DateFormat.getTimeInstance() 

->下午4:00:00

这个代码为我工作!

Date d = new Date();
    CharSequence s = android.text.format.DateFormat.format("MM-dd-yy hh-mm-ss",d.getTime());
    Toast.makeText(this,s.toString(),Toast.LENGTH_SHORT).show();