Aellopos
Aellopos

Reputation: 101

UWP - How do I convert date from calendar date picker to specified date format

I have in my project couple of calendar date picker controls. I am using code below to get date from them

enter image description here

How can I parse this to specific DateTime format ? For example to dd.mm.yyyy.

Upvotes: 1

Views: 3181

Answers (2)

Julien Shepherd
Julien Shepherd

Reputation: 103

It looks like the CalendarDatePicker.Date property is a nullable DateTimeOffset. You can access the associated DateTime object and get an array of strings that represent the date in various formats like this:

DateTimeOffset myDateTimeOffset = myCalendarDatePicker.Date ?? default(DateTimeOffset);
DateTime myDateTime = myDateTimeOffset.DateTime;
var formatArray = myDateTime.GetDateTimeFormats();
string desiredDateTimeFormat = formatArray[index];

Take a look over what formats are returned in the array of strings in order to choose your desired one.

Upvotes: 0

Sunteen Wu
Sunteen Wu

Reputation: 10627

DateTime.ToString(String) method can define custom format for DateTime. So we need to get out the DateTime type value from the CalendarDatePicker.Date property. Nullable structure has value property can get a valid underlying value. Code as follows can parse the date:

var date = arrivalCalendarDatePicker.Date;
DateTime time = date.Value.DateTime;
var formatedtime = time.ToString("dd.mm.yyyy");
System.Diagnostics.Debug.WriteLine(formatedtime);

Upvotes: 3

Related Questions