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


当前回答

使用Time类中的构建!

Time time = new Time();
time.set(0, 0, 17, 4, 5, 1999);
Log.i("DateTime", time.format("%d.%m.%Y %H:%M:%S"));

其他回答

Try:

event.putExtra("startTime", "10/05/2012");

当你访问传递的变量时:

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse(bundle.getString("startTime"));

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

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

类型日期

EEE:日(星期一) MMMM:完整的月份名称(十二月)// MMMM二月 MMM:文字中的月份(12月) 月(12) dd: 2个字符的天(03) d: 1个字符的天(3) 小时(12) mm:分钟(50) ss:秒(34) yyyy: Year (2022) // yyyy和yyyy相同 年(2022年) zzz: GMT+05:30 a:(上午/下午) aa:(上午/下午) aaa:(上午/下午) aaaa:(上午/下午)

使用SimpleDateFormat

是这样的:

event.putExtra("starttime", "12/18/2012");

SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Date date = format.parse(bundle.getString("starttime"));

日期格式类工作与作弊代码,使日期。就像

07, MMM ->七月,MMMM ->七月 EEE ->星期二,EEEE ->星期二 z -> EST, zzz -> EST, zzzz ->东部标准时间

你可以在这里查看更多的作弊。