[英]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. 我在iOS应用程序(使用xamarin)中使用了一个日期选择器和时间选择器,并且试图检索用户选择的日期和时间以在代码中的其他位置使用。 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. 我想获取类似日期
2016-05-24
或类似时间15:18:50
的信息。 I realize I can use regex for this but I was wondering if there is a simple way to format dates. 我意识到我可以为此使用正则表达式,但是我想知道是否存在一种简单的格式化日期的方法。
Since UIDatePicker.Date
returns nsdate
you could convert it to DateTime first and supply required format to ToString
method. 由于
UIDatePicker.Date
返回nsdate
您可以nsdate
其转换为DateTime并向ToString
方法提供所需的格式。
var dateTime = DateTime.SpecifyKind(ContactTimePicker.Date, DateTimeKind.Unspecified);
var selectedDate = dateTime.ToString("yyyy-MM-dd");
var selectedTime= dateTime.ToString("HH:mm:ss");
If ContactDatePicker.Date
type is DateTime
you can use ToShortDateString()
and ToShortTimeString()
or ToLongTimeString
: 如果
ContactDatePicker.Date
类型为DateTime
,则可以使用ToShortDateString()
和ToShortTimeString()
或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: 根据UIDatePicker的文档,
Date
属性返回一个NSDate
,但是对DateTime
进行了隐式转换,因此您可以执行以下操作:
DateTime date = ContactDatePicker.Date //Implicit conversion
var selectedDate = date.ToShortDateString();
var selectedTime = date.ToLongTimeString();
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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.