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.
Related
Trying to figure out how to add a century prefix (19 or 20) to a birth date. Does anyone see how to write this in a better way?
public string GetCenturyPrefix(string socSecNo)
{
string prefix = string.Empty;
try
{
var currentDate = DateTime.Now;
var birthDayTemp = socSecNo.Substring(0, 6);
var yy = birthDayTemp.Substring(0, 2);
var mm = birthDayTemp.Substring(2, 2);
var dd = birthDayTemp.Substring(4, 2);
birthDayTemp = yy + "-" + mm + "-" + dd;
var birthDay = Convert.ToDateTime(birthDayTemp);
var totalDays = currentDate - birthDay;
var age = totalDays.TotalDays / 365;
var yearsAfter2000 = Convert.ToInt32(currentDate.Year.ToString().Substring(2, 2));
if (age > yearsAfter2000)
{
prefix = "19";
}
else
{
prefix = "20";
}
}
catch (Exception)
{
}
return prefix;
}
Don't use Substring to parse a string value into a DateTime. .Net has very robust methods created for you to do this conversion.
Here I'm using DateTime.TryParseExact(), which lets me specify the exact format I expect dates values to be provided in. The method returns true or false indicating if the value is in that supplied format. No need to use exceptions to control logic flow.
public string GetCenturyPrefix(string socSecNo)
{
// Check if you're able to parse the incoming value
// in the format "yyMMdd".
if (!DateTime.TryParseExact(socSecNo, "yyMMdd", CultureInfo.InvariantCulture,
DateTimeStyles.None, out DateTime parsedDateTime))
{
// Do something if the input can't be parsed in that format.
// In this example I'm throwing an exception, but you can also
// return an empty string.
throw new Exception("Not valid date format");
}
// Extract only the Year portion as a 4 digit string,
// and return the first 2 characters.
return parsedDateTime.ToString("yyyy").Substring(0, 2);
}
You can do it like (year/100)+1 but put {0:n0} format to your .ToString("{0:n0}") this could be the logic and for the if else it can stay like that. This should be working for any century as I tried on calculator.
I can't seem to get my head around this but what would be the best approach for displaying a list of upcoming events?
At the moment I have a list of json events being displayed. All these events have a specific date on them.
2016-04-01T13:15:00
Most of the events have passed so i do not need to have them shown. How would i go about only showing the upcoming events?
The main thing I cant figure out is how to get todays date...
This is the code I used to display the events.
async void PopulateTableWithData()
{
var service = new Data.RestService();
var response = await service.GetEventItemsAsync();
Debug.WriteLine("JSON RESULTS FOUND: " + response.Count + "events");
listView.ItemsSource = response; // Display data in listview
/**ITEM SELECTED EVENT**/
listView.ItemSelected += (sender, e) =>
{
var i = (listView.ItemsSource as List<EventItems>).IndexOf(e.SelectedItem as EventItems);
string title = response[i].Title;
string description = response[i].EventDescription;
string location = response[i].EventLocation;
string startTime = response[i].EventStartTime;
string endTime = response[i].EventEndTime;
string rowKey = response[i].RowKey;
Navigation.PushAsync(new EventsWebviewPage(title, description, location, startTime, endTime, ReplaceString(rowKey, " ", "%20")));
};
}
Would I have to use some form of DateTime?
Can anyone give me some guidance?
Thanks
EDITED
async void PopulateTableWithData()
{
var service = new Data.RestService();
var response = await service.GetEventItemsAsync();
Debug.WriteLine("JSON RESULTS FOUND: " + response.Count + "events");
//listView.ItemsSource = response; // Display data in listview
for(int i = 0; i < response.Count; i++)
{
// Split raw json date
string[] splitRawDateTime = response[i].EventEndTime.Split('T');
string[] splitRawDate = splitRawDateTime[0].Split('-');
string eventYear = splitRawDate[0];
string eventMonth = splitRawDate[1];
string eventDay = splitRawDate[2];
// Compare dates and display events according to date
DateTime currentDateTime = DateTime.Now;
DateTime eventDateTime = new DateTime(int.Parse(eventYear), int.Parse(eventMonth), int.Parse(eventDay), 0, 0, 0);
int compareDates = DateTime.Compare(eventDateTime, currentDateTime);
List<EventItems> upcomingEvents = new List<EventItems>();
if (compareDates < 0)
{
Debug.WriteLine("Event date {0} is earlier then current date {1}", eventDateTime, currentDateTime);
}
else
{
Debug.WriteLine("Event date {0} is later then current date {1}", eventDateTime, currentDateTime);
upcomingEvents.Add(response[i]);
}
listView.ItemsSource = upcomingEvents;
}
}
}
I have just tried the above code and it seems to be working but how do I only display the upcoming events?
I believe its an issue with my placement of
listView.ItemsSource = response;
I know im probably doing something wrong here. Can anyone help?
You can get the current date and time by using DateTime.Now
You can also create a DateTime object from a string representation of a date by using one of the DateTime.Parse() functions. Then you can compare the two dates by using comparison operators: <, <=, >, >=, ==
Edit: You could try it his way:
async void PopulateTableWithData()
{
var service = new Data.RestService();
var response = await service.GetEventItemsAsync();
Debug.WriteLine("JSON RESULTS FOUND: " + response.Count + "events");
//listView.ItemsSource = response; // Display data in listview
//Instantiate the list of upcoming events before the loop
List<EventItems> upcomingEvents = new List<EventItems>();
for(int i = 0; i < response.Count; i++)
{
// Split raw json date
string[] splitRawDateTime = response[i].EventEndTime.Split('T');
string[] splitRawDate = splitRawDateTime[0].Split('-');
string eventYear = splitRawDate[0];
string eventMonth = splitRawDate[1];
string eventDay = splitRawDate[2];
// Compare dates and display events according to date
DateTime currentDateTime = DateTime.Now;
DateTime eventDateTime = new DateTime(int.Parse(eventYear), int.Parse(eventMonth), int.Parse(eventDay), 0, 0, 0);
int compareDates = DateTime.Compare(eventDateTime, currentDateTime);
if (compareDates < 0)
{
Debug.WriteLine("Event date {0} is earlier then current date {1}", eventDateTime, currentDateTime);
}
else
{
Debug.WriteLine("Event date {0} is later then current date {1}", eventDateTime, currentDateTime);
//Populate the list of upcoming events
upcomingEvents.Add(response[i]);
}
}
//Display the list of upcoming events
listView.ItemsSource = upcomingEvents;
}
I am using the fullcalendar,
but in IE 10 or 11 the events are not render correct,
I have this:
public static List<DiaryEvent> LoadAllAppointmentsInDateRange(double start, double end)
{
var fromDate = ConvertFromUnixTimestamp(start);
var toDate = ConvertFromUnixTimestamp(end);
using (LolaBikeContext ent = new LolaBikeContext())
{
var rslt = ent.AppointmentDiarys.Where(s => s.DateTimeScheduled >= fromDate && System.Data.Entity.DbFunctions.AddMinutes(s.DateTimeScheduled, s.AppointmentLength) <= toDate);
List<DiaryEvent> result = new List<DiaryEvent>();
foreach (var item in rslt)
{
DiaryEvent rec = new DiaryEvent();
rec.ID = item.Id;
rec.SomeImportantKeyID = item.SomeImportantKey;
rec.StartDateString = item.DateTimeScheduled.ToString("MMMM/dd/yyyy"); // "s" is a preset format that outputs as: "2009-02-27T12:12:22"
rec.StarEvent = item.DateTimeScheduled.ToString("HH:mm"); // ParseExact(start, "HH:mm", CultureInfo.CurrentCulture).ToString(); //item.DateTimeScheduled.ToString("MMMM/dd/yyyy");
rec.EndDateString = item.DateTimeScheduled.AddMinutes(item.AppointmentLength).ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffffffzzz");// "yyyy-MM-ddTHH:mm:ss.fffZ"); // field AppointmentLength is in minutes
rec.Title = item.Title;// +" - " + item.AppointmentLength.ToString() + " mins";
rec.AppointmentLength = item.AppointmentLength.ToString();
rec.StatusString = Enums.GetName<AppointmentStatus>((AppointmentStatus)item.StatusENUM);
rec.StatusColor = Enums.GetEnumDescription<AppointmentStatus>(rec.StatusString);
string ColorCode = rec.StatusColor.Substring(0, rec.StatusColor.IndexOf(":"));
rec.ClassName = rec.StatusColor.Substring(rec.StatusColor.IndexOf(":") + 1, rec.StatusColor.Length - ColorCode.Length - 1);
rec.StatusColor = ColorCode;
result.Add(rec);
}
return result;
}
}
and especially this line:
rec.EndDateString = item.DateTimeScheduled.AddMinutes(item.AppointmentLength).ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffffffzzz");// is not rendering correct.
I have read that it has to be in: ISO 8601, so I have looked at this thread:
Given a DateTime object, how do I get an ISO 8601 date in string format?
but that doesnt work. IE is rendering the events not correct
Thank you!!
see the different pictures
The correct image:
I think youare missing the "s" format specifier, which is described as Sortable date/time pattern; conforms to ISO 8601
The EventStart comes in ISO 8601 format and you will need to convert it. you can follow this example to convert current to ISO 8601:
DateTime.UtcNow.ToString ( "s", System.Globalization.CultureInfo.InvariantCulture )
Here's a post about that : Link
As for your code try this instead for your startdatestring and enddatestring:
rec.StartDateString = item.DateTimeScheduled.ToString("s");
rec.EndDateString = item.DateTimeScheduled.AddMinutes(item.AppointmentLength).ToString("s");
I have a WebService which return DateTime Field.
I get a result /Date(1379048144000)/ but
i want just 1379048144000 how can i achieve that.
[WebMethod]
public DateTime GetServerDate()
{
return DateTime.Now;
}
by setting Header Content-Type: application/json; charset=utf-8; i got a result like /Date(1379048144000)/.
You could change your WS to return a long with the value of the DateTime. The value to return is the number of milliseconds since the Unix Epoch (01/01/1970). This could be done with an extension method on DateTime something like:
public static class DateTimeExtensions
{
...
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1);
public static long ToUnixTime(this DateTime dateTime)
{
return (dateTime - UnixEpoch).Ticks / TimeSpan.TicksPerMillisecond;
}
...
}
And your web service method might look something like:
public long GetMyDate(...)
{
DateTime dateTime = ...;
return dateTime.ToUnixTime();
}
with Json.NET :
string date = Newtonsoft.Json.JsonConvert.SerializeObject(DateTime.Now);
in client side you can use this function to show a right date to client(I use it on my projects):
function parseJsonDate(jsonDate) {
var offset = new Date().getTimezoneOffset() * 60000;
var parts = /\/Date\((-?\d+)([+-]\d{2})?(\d{2})?.*/.exec(jsonDate);
if (parts[2] == undefined) parts[2] = 0;
if (parts[3] == undefined) parts[3] = 0;
d = new Date(+parts[1] + offset + parts[2] * 3600000 + parts[3] * 60000);
date = d.getDate() + 1;
date = date < 10 ? "0" + date : date;
mon = d.getMonth() + 1;
mon = mon < 10 ? "0" + mon : mon;
year = d.getFullYear();
return (date + "." + mon + "." + year);
};
This function is return right date in format: dd.mm.yyyy, but you can change it if you need. I hope that I help you.
U can always solve your problem when sending a date in a JSON object to JS by converting the date as follows:
var myJSDate = (new Date(parseInt(obj.MyDate.substr(6)))).toJSON();
Where obj.Date contains the date you wanna format.
Then u'll get something like this: "2013-10-25T18:04:17.289Z"
U can always check it in Chrome console by writing:
(new Date()).toJSON();
Hope this helps!
There are two solutions:
client side:
function ToJavaScriptDate(value) {
var pattern = /Date\(([^)]+)\)/;
var results = pattern.exec(value);
var dt = new Date(parseFloat(results[1]));
return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
}
It is possible to need alsou to convert into data object
var date = new Date(xxx)
Server side:
Newtonsoft.Json.JsonConvert.SerializeObject(your_object)
Simply write like this to convert your date string in JSON format.
date = "{" + date + "}";
try regex:
var jsonDate = #"/Date(1379048144000)/";
var regex = /-?\d+/;
var jsonDate = re.exec(jsonDate);
var dateOriginal = new Date(parseInt(m[0]));
I have a textfield that has a date with the format "12/23/2010".Is there away for me to get the number 23 using watin ie get number from textfield;i'm gonna use it like this.
1.Get datetime 12/23/2010 and get number '23'
2.substract 2 from 23 and store it somewhere[ie: 23 - 2 = 21]
3.Insert the new datetime number [ie:12/21/2010 ]
string myDate = browser.TextField(Find.ByName("myTextField")).Value;
DateTime time = = new DateTime();
time2 = time - 2;
browser.TextField(Find.ByName("myTextField")).TypeText(time2);
Is this possible?or should i be looking to another way.Ask the user to insert the data instead.
Try this :
string myDate = browser.TextField(Find.ByName("myTextField")).Value;
DateTime time = = new DateTime();
if(DateTime.TryParse(myDate, out time);) {
Console.WriteLine(time.Month);
}
else {
//Not a valid date.
}