更改c# Xamarin中的日期格式
本文关键字:日期 格式 Xamarin 更改 | 更新日期: 2023-09-27 18:13:44
我在Android上工作Xamarin。我在我的项目中使用了DatePicker
。代码如下:
OnCreate
方法内部代码。
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Activity_register);
tiebirthdate = FindViewById<TextInputEditText>(Resource.Id.tiebirthdate);
tiebirthdate.Click += DateSelect_OnClick;
}
void DateSelect_OnClick(object sender, EventArgs e)
{
DatePickerFragment frag = DatePickerFragment.NewInstance(delegate (DateTime time)
{
var dateAndTime = time;
var tt = dateAndTime.Date;
tiebirthdate.Text = tt.ToString("dd/MM/yyyy");
});
frag.Show(FragmentManager, DatePickerFragment.TAG);
}
创建类。
class DatePickerFragment : DialogFragment,
DatePickerDialog.IOnDateSetListener
{
public static readonly string TAG = "X:" + typeof(DatePickerFragment).Name.ToUpper();
// Initialize this value to prevent NullReferenceExceptions.
Action<DateTime> _dateSelectedHandler = delegate { };
public static DatePickerFragment NewInstance(Action<DateTime> onDateSelected)
{
DatePickerFragment frag = new DatePickerFragment();
frag._dateSelectedHandler = onDateSelected;
return frag;
}
public override Dialog OnCreateDialog(Bundle savedInstanceState)
{
DateTime currently = DateTime.Now;
DatePickerDialog dialog = new DatePickerDialog(Activity,
this,
currently.Year,
currently.Month,
currently.Day);
return dialog;
}
public void OnDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
DateTime selectedDate = new DateTime(year, monthOfYear + 1, dayOfMonth);
_dateSelectedHandler(selectedDate);
}
}
我尝试后,最后我设置DateTime
像这样的格式"dd/MM/yyyy"
。但是我的服务器需要像"yyyy-MM-dd'T'HH:mm:ss'Z'"
这样的日期格式。那么如何更改DateTime
格式,如upper.
tiebirthdate.Text = dateAndTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture);
你可以试试这个
可以使用DateTime。ParseExact方法。参考MSDN页面中的示例