How to format correctly according to the device configuration date and time when having a year, month, day, hour and minute?
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
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());
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();
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());
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"));
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