1

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!

Anas Alweish
  • 2,818
  • 4
  • 30
  • 44

2 Answers2

1

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);
Muhammad Hamza Shahid
  • 956
  • 1
  • 15
  • 23
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);
Malte Goetz
  • 792
  • 6
  • 16