Xamarin forms display events which are upcoming - c#

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;
}

Related

Combining 2 .csv Files as well as sorting the content by date with different time format

I am currently working on a task where i want to take the content of 2 .csv files and put them in one new .csv file as well as sorting the content by date.
so far so good... the problem is that the content uses several datetime formats
can one of you guys help me with this?
here ist the code i have so far
//reading the raw files
string[] rawdata = File.ReadAllLines(PathInRaw);
string[] rawdataTick = File.ReadAllLines(PathInRawTick);
//clearing existing file and writing in the new content
File.WriteAllText(PathOut, " ");
File.AppendAllLines(PathOut, rawdata);
File.AppendAllLines(PathOut, rawdataTick);
//changing date format??? which i dont get to work
string[] list = { };
int counter = 0;
foreach (string line in File.ReadAllLines(PathOut))
{
column = line.Split(';');
column[0] = DateTime.Now.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
list[counter] = Convert.ToString(column);
counter++;
}
File.WriteAllText(PathOut, " ");
File.WriteAllLines(PathOut, list);
//sorting it
DateTime d = DateTime.MinValue;
var query = from line in File.ReadLines(PathOut)
let fields = line.Split(';')
let dateParsed = DateTime.TryParse(fields[0], out d)
let dateObject = dateParsed ? d : DateTime.MinValue
orderby dateParsed, dateObject
select line;
List<string> sortedLines = query.ToList();
File.WriteAllText(PathOut, " ");
File.WriteAllLines(PathOut, sortedLines);
The Dateformates I have in the .csv are
5/30/2018 2:48:57 PM (MM/dd/yyyy HH:mm:ss a)
06.01.2018 06:12:19 (MM.dd.yyyy HH:mm:ss)
20180601 16:21:50 (yyyyMMdd HH:mm:ss)
The first two formats should be standard enough to be parsed with DateTime.Parse(...). The last one is a bit too custom for this to catch, so implementing a parsing method will be your best bet.
private static DateTime ParseDateTime(string dateTime) {
DateTime? d1 = null;
try {
d1 = DateTime.Parse(dateTime);
}
catch { }
if (d1 == null) {
try {
d1 = DateTime.ParseExact(dateTime, "yyyyMMdd HH:mm:ss", CultureInfo.InvariantCulture);
}
catch { }
}
return (DateTime)d1;
}
Here the first try catch block will catch all the standard formats and if it does not, the d1 object will still be null so then we will try your custom format. Finally we cast back to a non-nullable DateTime object to make it easier to work with.
A way to use this would be the following, where you would replace the two hard coded lists of DateTime strings with reading from your files.
List<string> rawLines1 = new List<string>() { "5/30/2018 2:48:57 PM", "06.01.2018 06:12:19" };
List<string> rawLines2 = new List<string>() { "20180601 16:21:50" };
List<string> rawLines = new List<string>();
rawLines.AddRange(rawLines1);
rawLines.AddRange(rawLines2);
List<DateTime> parsedDateTimes = new List<DateTime>();
foreach (string rawLine in rawLines) {
parsedDateTimes.Add(ParseDateTime(rawLine));
}
parsedDateTimes = parsedDateTimes.OrderBy(x => x).ToList();
The very last line takes care of sorting back into the order with the oldest at the top. If you want this reversed, replace .OrderBy(x => x) with .OrderByDescending(x => x)
From here you can write back out to your output file.

Correct format to input date with time of the day

I want to be able to calculate the time in hours and minutes elapsed between, say, 12:35pm 02/13/2016 to 1:45pm 02/14/2016, but can't figure out the correct format to input it.
EDIT: Should add that the span between the times will be stored in an arraylist, one span per customer.
Basically, you need something like this:
var dateA = new DateTime(2016,2,13,12,35,0);
var dateB = new DateTime(2016,2,14,1,45,0);
var timespan = dateB - dateA;
var hours = timespan.Hours;
bar minutes = timespan.Minutes;
Here's how I would go about it:
Func<string, DateTime?> tryParse = t =>
{
DateTime output;
if (DateTime.TryParseExact(
t,
new [] { "h:mmtt MM/dd/yyyy" },
System.Globalization.CultureInfo.CurrentCulture,
System.Globalization.DateTimeStyles.AssumeLocal,
out output))
{
return output;
}
return null;
};
var dt1 = tryParse("12:35pm 02/13/2016");
var dt2 = tryParse("1:45pm 02/14/2016");
TimeSpan? ts = null;
if (dt1.HasValue && dt2.HasValue)
{
ts = dt2.Value.Subtract(dt1.Value);
}
if (ts.HasValue)
{
Console.WriteLine(
String.Format(
"{0} hours & {1} minutes",
ts.Value.Hours,
ts.Value.Minutes));
}

Rendering in IE with fullcalendar

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");

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.

How to add timespan values in list

In the below code i will get a list of time span values. I need to add all the time span values and that value has to be stored in string.How to achieve this i tried a lot but I can't find answer for this.
Thanks in Advance.
List<TimeSpan> objList = new List<TimeSpan>();
string totalIntervalTime = string.Empty;
private void Resume_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox2.Text))
{
textBox3.Text = DateTime.Now.ToLongTimeString();
//objPausetmr.Tick += new EventHandler(objPausetmr_Tick);
//objPausetmr.Stop();
tmrObj.Start();
DateTime pausetime = Convert.ToDateTime(textBox2.Text);
DateTime startTime = Convert.ToDateTime(textBox3.Text);
TimeSpan difference = pausetime - startTime;
string intervalDifference = difference.ToString();
richTextBox1.Text = intervalDifference;
TimeSpan tltTime = TimeSpan.Zero;
objList.Add(difference);
foreach (TimeSpan tmVal in objList)
{
tltTime.Add(tmVal);
}
totalIntervalTime = tltTime.ToString();
//MessageBox.Show(interval_Time.ToString());
}
else
{
MessageBox.Show("Please set the Pause time");
}
}
Assuming you want to add values of all time spans into single time span.
DateTime and TimeSpan are immutable structs. All operations using them return new instances. So you need to store result of operation in a TimeSpan value (normally just updating exisintg one is fine)
var totalTime = TimeSpan.Zero;
foreach (TimeSpan currentValue in objList)
{
totalTime = totalTime + currentValue;
}
Usage of + covered in details in TimeSpan.Addition Operator MSDN article.
Alternatively you can use Enumerable.Aggregate:
var totalTime = objList.Aggregate(
(accumulatedValue,current) => accumulatedValue + current);
You can try something like
string s = String.Join(",",objList.Select(x => x.ToString()));
Have a look at
String.Join Method
Enumerable.Select
Using objList.Select(x => x.ToString()) you can determine the format output you want
Span.ToString Method (String)

Categories