Tyler Kelly
Tyler Kelly

Reputation: 574

How to retrieve formatted version of date from date picker backend

I have a date picker and time picker I am using in my iOS application (using xamarin) and I am trying to retrieve the date and time selected by the user to use elsewhere in the code. My problem is that I am not sure how to retrieve just the date or just the time. For example I have this following code to retrieve the date:

// not getting proper date format!
var selectedDate = ContactDatePicker.Date.ToString ();
var selectedTime= ContactTimePicker.Date.ToString ();
Console.WriteLine ("Here: {0}, {1}", selectedDate, selectedTime);

But it outputs the entirety of the of the date and time for each variable like so:

Here: 2016-05-24 15:18:50 +0000, 2016-05-24 15:18:50 +0000

I would like to get something like 2016-05-24 for date or something like 15:18:50 for time. I realize I can use regex for this but I was wondering if there is a simple way to format dates.

Upvotes: 0

Views: 654

Answers (3)

Tyler Kelly
Tyler Kelly

Reputation: 574

Thanks for the info guys I ended up using:

// explicitly convert NSDate to DateTime to change format
DateTime date = (DateTime)ContactDatePicker.Date;
DateTime time = (DateTime)ContactTimePicker.Date;

// able to overload ToString() method with argument to change format
var selectedDate = date.ToString ("d");
var selectedTime = time.ToString ("HH:mm:ss");

Upvotes: 0

Hari Prasad
Hari Prasad

Reputation: 16956

Since UIDatePicker.Date returns nsdate you could convert it to DateTime first and supply required format to ToString method.

var dateTime = DateTime.SpecifyKind(ContactTimePicker.Date, DateTimeKind.Unspecified);
var selectedDate = dateTime.ToString("yyyy-MM-dd");
var selectedTime= dateTime.ToString("HH:mm:ss");        

Upvotes: 3

Arturo Menchaca
Arturo Menchaca

Reputation: 15982

If ContactDatePicker.Date type is DateTime you can use ToShortDateString() and ToShortTimeString() or ToLongTimeString:

var selectedDate = ContactDatePicker.Date.ToShortDateString();
var selectedTime = ContactTimePicker.Date.ToLongTimeString();

//Output:
2016-05-24
15:18:50

According to documentation of UIDatePicker, Date property returns a NSDate, but there are an implicit conversion to DateTime, so you can do something like this:

DateTime date = ContactDatePicker.Date    //Implicit conversion
var selectedDate = date.ToShortDateString();
var selectedTime = date.ToLongTimeString();

Upvotes: 1

Related Questions