使用 Java 中的 getDateTimeInstance() 設定日期格式
為了設定日期格式,我們來看看 DateFormat.SHORT 和 DateFormat.LONG 常量。它們都會顯示不同的模式。
這裡,我們使用 getDateTimeInstance() 方法設定日期格式。使用該方法來獲取日期和時間格式。
對於 DateFormat.SHORT 常量 -
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT); System.out.println(dateFormat.format(calendar.getTime()));
對於 DateFormat.LONG 常量 -
dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG); System.out.println(dateFormat.format(calendar.getTime()));
以下是示例 -
示例
import java.text.DateFormat; import java.util.Calendar; public class Demo { public static void main(String s[]) { Calendar calendar = Calendar.getInstance(); // for SHORT date-time DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT); System.out.println(dateFormat.format(calendar.getTime())); // for LONG date-time dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG); System.out.println(dateFormat.format(calendar.getTime())); } }
輸出
11/22/18 9:57 AM November 22, 2018 9:57:26 AM UTC
廣告