简体   繁体   中英

Formatting the JSON date value

I am accessing data from an API, and it returns the date value in the JSON as formatted as 2014-12-01. I have assigned this to the class and bound to a textblock within a listbox control, and it displays fine. However, is there a way that I can display the date in the format "Thursday 20th Decemeber 2014".

I am using c# .NET for windows phone 8. Code Snippet below on how the data is returned.

         while (count < ja.Count) {
                SkiddleEvents content = new SkiddleEvents();

                //EVENT DETAILS
                if (ja[count]["imageurl"] != null) {
                    content.str_eventImage = ja[count]["imageurl"].ToString();
                }
                else {
                    Uri imageUrl = new Uri("/Assets/placeholder.jpg", UriKind.Relative);
                    content.str_eventImage = imageUrl.ToString();
                }
                content.str_eventID = ja[count]["id"].ToString();
                content.str_eventName = ja[count]["eventname"].ToString();
                content.str_eventDate = ja[count]["date"].ToString();
                content.str_eventAddress = ja[count]["venue"]["address"].ToString() + ", " + ja[count]["venue"]["town"].ToString();
                content.str_venueID = ja[count]["venue"]["id"].ToString();

                //add the content to the list box and increase the count
                contentList.Add(content);
                count++;
            } 

Change this line to:

DateTime eventDate = DateTime.MinValue;
if (DateTime.TryParse(ja[count]["date"], out eventDate))
{
    content.str_eventDate = string.Format("{0:dddd dd}{1} {0:MMMM yyyy}",
        eventDate, 
        (eventDate.Day == 1) 
                         ? "st"
                         : (eventDate.Day == 2)
                               ? "nd"
                               : (eventDate.Day == 3)
                                     ? "rd"
                                     : "th"); 
}

That should get you the format you want.

DateTime formatting taken from here: Getting day suffix when using DateTime.ToString()

Convert the JSON date field to a DateTime object.

DateTime dt = DateTime.Parse(content.str_eventDate = ja[count]["date"].ToString());
string formattedDate = dt.ToString("G");

See here for the custom date / time formats.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM