How to display Date like device date time format i

2019-08-07 19:06发布

问题:

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);