How to format date and time in Android?

前端 未结 24 1283
面向向阳花
面向向阳花 2020-11-22 00:51

How to format correctly according to the device configuration date and time when having a year, month, day, hour and minute?

相关标签:
24条回答
  • 2020-11-22 01:04

    Date to Locale date string:

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

    Options:

       DateFormat.getDateInstance() 
    

    - > Dec 31, 1969

       DateFormat.getDateTimeInstance() 
    

    -> Dec 31, 1969 4:00:00 PM

       DateFormat.getTimeInstance() 
    

    -> 4:00:00 PM

    0 讨论(0)
  • 2020-11-22 01:04

    Back to 2016, When I want to customize the format (not according to the device configuration, as you ask...) I usually use the string resource file:

    in strings.xml:

    <string name="myDateFormat"><xliff:g id="myDateFormat">%1$td/%1$tm/%1$tY</xliff:g></string>
    

    In Activity:

    Log.d(TAG, "my custom date format: "+getString(R.string.myDateFormat, new Date()));
    

    This is also useful with the release of the new Date Binding Library.

    So I can have something like this in layout file:

    <TextView
        android:id="@+id/text_release_date"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:padding="2dp"
        android:text="@{@string/myDateFormat(vm.releaseDate)}"
        tools:text="0000"
        />
    

    And in java class:

        MovieDetailViewModel vm = new MovieDetailViewModel();
        vm.setReleaseDate(new Date());
    
    0 讨论(0)
  • 2020-11-22 01:08

    This code work for me!

    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();
    
    0 讨论(0)
  • 2020-11-22 01:09

    Use these two as a class variables:

     public java.text.DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
     private Calendar mDate = null;
    

    And use it like this:

     mDate = Calendar.getInstance();
     mDate.set(year,months,day);                   
     dateFormat.format(mDate.getTime());
    
    0 讨论(0)
  • 2020-11-22 01:12

    Use build in Time class!

    Time time = new Time();
    time.set(0, 0, 17, 4, 5, 1999);
    Log.i("DateTime", time.format("%d.%m.%Y %H:%M:%S"));
    
    0 讨论(0)
  • Here is the simplest way:

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

    and If you are looking for patterns, check this https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

    0 讨论(0)
提交回复
热议问题