【问题标题】:Converting ISO8061 Date to EN-US Through Binding通过绑定将 ISO8061 日期转换为 EN-US
【发布时间】:2018-03-30 15:48:06
【问题描述】:

我正在尝试获取我存储的 ISO8061 日期时间 (yyyy/MM/dd HH:mm:ss) 并将其转换为美国短日期 (MM/dd/yyyy) 以显示在我的数据网格中。我尝试在绑定时使用 stringformat 以及创建转换器来完成这项工作。

在以下示例中:cal_date 是通过 SQLite 数据库中的数据适配器填充的数据表列。

这是模型的 sn-p:

    public DataTable RetrieveToolRoster()
    {
        string db_command = "SELECT [id], [description], [serial], [model], [manufacturer], [location], [cal_interval], " +
                            "[cal_date], [cal_due], [checked_out], [tool_lock] FROM inventory WHERE [cal_date] IS NOT NULL ORDER BY [id] ASC;";
        DataTable tr_dataTable = new DataTable();
        using (SQLiteConnection db_connection = new SQLiteConnection(Properties.Settings.Default.db_connectionstring))
        {
            using (SQLiteDataAdapter db_dataAdapter = new SQLiteDataAdapter(db_command, db_connection))
                try
                {
                    db_connection.Open();
                    db_dataAdapter.Fill(tr_dataTable);
                    db_connection.Close();
                    return tr_dataTable;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error:\r\n" + ex.Message);
                    return null;
                }
        }
    }

以下是我尝试过的一些示例。

在通过 StringFormat 绑定时尝试格式化

Binding="{Binding cal_date, StringFormat=MM/dd/yyyy}"/>

Binding="{Binding cal_date, StringFormat='MM/dd/yyyy'}"/>

Binding="{Binding cal_date, StringFormat=d}"/>

Binding="{Binding cal_date, ConverterCulture='en-US', StringFormat=d}"/>

Binding="{Binding cal_date, StringFormat={}{0:MM/dd/yyyy}}"/>

Binding="{Binding cal_date, StringFormat='{}{0:MM/dd/yyyy}'}"/>

尝试通过转换器格式化:

XAML

<DataGridTextColumn Header="Calibration Date:"
                            Width="*"
                            Binding="{Binding cal_date, Converter={StaticResource ISOtoENUS}}"/>

C#

class ISO8061toENUSConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is string)
        {
            var dt = string.Format("{0:MM/dd/yyyy}", value);
            return dt;
        }
        return string.Empty;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();

所有结果都相同,返回 (yyyy/MM/dd HH:mm:ss)

我已经在这里待了将近两天了。我已经搜索和搜索。我什至尝试从询问他们在哪里工作的问题中实现代码 sn-ps,但无济于事。我做错了什么?

【问题讨论】:

  • 您不希望转换器中只有string.Format,您希望DateTime.Parse(甚至更好的DateTime.ParseExact)首先获得未格式化的日期时间。
  • 这很完美。我将字符串解析为日期时间,然后返回 datetime.tostring("mm/dd/yyyy")。

标签: c# wpf xaml mvvm


【解决方案1】:

编辑

如果 CalDate 是一个字符串,那么您可以使用 DateTime.TryParse 修改您的转换器:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    if (value is string)
    {
        DateTime parsedDate = DateTime.MinValue;
        if (DateTime.TryParse(value.ToString(), null, DateTimeStyles.RoundtripKind, out parsedDate))
        {
            return string.Format("{0:MM/dd/yyyy}", parsedDate);
        }
    }
    return string.Empty;
}

使用 DateTime 对象

我认为转换器的方式是正确的,假设 cal_date 属性是一个 DateTime 对象:

private DateTime _calDate;
public DateTime CalDate
{
     get { return _calDate; }
     set
     {
         _calDate = value;
         NotifyPropertyChanged();
     }
 }

然后更改您的转换器以使用 DateTime 对象:

public class ISO8061toENUSConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is DateTime)
        {
            return string.Format("{0:MM/dd/yyyy}", value);
        }
        return string.Empty;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

这是我使用的绑定:

DataGridTextColumn Header="Calibration Date:"
                        Width="*"
                        Binding="{Binding CalDate, Mode=OneWay, Converter={StaticResource ISOtoENUS}}"/>

你应该得到正确的价值(我测试过它并为我工作)。

【讨论】:

  • 我似乎遗漏了“cal_date”实际上是数据表中的列的部分。抱歉...“cal_date”是 SQLite 数据库中的数据列,日期以 ISO8061 格式存储为文本。
猜你喜欢
  • 2015-01-18
  • 1970-01-01
  • 2021-01-27
  • 1970-01-01
  • 1970-01-01
  • 2011-01-31
  • 1970-01-01
  • 1970-01-01
  • 2021-02-24
相关资源
最近更新 更多