来自webservice的日期时间显示问题

时间:2012-04-16 21:04:27

标签: c# wpf wcf web-services rest

当我从其余的Web服务显示客户端时,我的日期时间非常困难,我的客户端wpf应用程序代码如下所示:

    public MainWindow()
    {
        InitializeComponent();
        string uriGroups = "http://localhost:8000/Service/Student";
        XDocument xDoc = XDocument.Load(uriGroups);

        foreach(var node in xDoc.Descendants("Student"))
        {

            GroupBox groupbox = new GroupBox();
            groupbox.Header = String.Format(node.Element("StudentID").Value);
            groupbox.Width = 100;
            groupbox.Height = 100;
            groupbox.Margin = new Thickness(2);

            TextBlock textBlock = new TextBlock();
            textBlock.Text = String.Format(node.Element("FirstName").Value + " " + (node.Element("LastName").Value));
            textBlock.TextAlignment = TextAlignment.Center;

            TextBlock textBlock1 = new TextBlock();
            textBlock1.Text = String.Format(node.Element("TimeAdded").Value);
            textBlock1.TextAlignment = TextAlignment.Center;
            textBlock1.VerticalAlignment = VerticalAlignment.Bottom;

            StackPanel stackPanel = new StackPanel();
            stackPanel.Children.Add(groupbox);

            stackPanel.Children.Add(textBlock);
            stackPanel.Children.Add(textBlock1);
            stackPanel.Margin = new Thickness(10);

            MainArea.Children.Add(stackPanel);
        }

    }

我的服务看起来像这样:

public class Student
{
    ....
            public DateTime TimeAdded;
        public string TimeAddedString
        {
            get
            {
                return this.TimeAdded.ToString("dd/MM/yyyy hh:mm:ss");
            }
        }

但输出如下:

enter image description here

我的客户端应用程序代码是否有办法截断或重新格式化?

2 个答案:

答案 0 :(得分:3)

您可以将其投射到DateTime,然后使用String.Format

以下是您可以使用的一种格式示例:

String.Format("{0:M/d/yyyy}", ((DateTime)node.Element("TimeAdded").Value))

您也可以使用DateTime.ToString(FORMAT)

((DateTime)node.Element("TimeAdded").Value).ToString("d");

我已假设.Value返回object,但如果它返回DateTime,则可以删除强制转换。

如果您在客户端收到字符串,则需要使用DateTime.Parse

(DateTime.Parse(node.Element("TimeAdded").Value)).ToString("d");
String.Format("{0:M/d/yyyy}", DateTime.Parse(node.Element("TimeAdded").Value))

答案 1 :(得分:2)

您正在使用TimeAdded ...但我认为您应该使用TimeAddedString

textBlock1.Text = String.Format(node.Element("TimeAdded").Value);

应该是

textBlock1.Text = String.Format(node.Element("TimeAddedString").Value);

我相信