How to display Date like device date time format in Android

眉间皱痕 提交于 2019-12-11 06:19:55

问题


I have a date:

var date = new DateTime(2017,6,14,13,0,0);

and a textview to display it. I'd like to display as '14/06/2017 13:00' when I set Date and time of the device to 'Use 24-hour format' and '16/06/2017 1:00 PM' when I un-check 'Use 24-hour format'.

How can I do?

Thank you!


回答1:


On Xamarin.Android it is a bit different than on Android as described in Muhammads answer:

var date = new DateTime(2017, 6, 14, 13, 0, 0);
var is24hour = Android.Text.Format.DateFormat.Is24HourFormat(this);
var format = is24hour ? "dd/MM/yyyy HH:mm" : "dd/MM/yyyy hh:mm tt";
var dtString = date.ToString(format);



回答2:


You can use following code to convert you date object in specific format

SimpleDateFormat dateFormat;
if (android.text.format.DateFormat.is24HourFormat(YourActivityName.this)) {
    // 24 hour format
    dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm");
}
else
{
    // 12 hour format
    dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
}
String newDate= dateFormat.format(date);
myTextView.setText(newDate);


来源:https://stackoverflow.com/questions/44542961/how-to-display-date-like-device-date-time-format-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!