user15101910
user15101910

Reputation:

Display Bar Chart in Xamarin.Forms Daily Count

I am working with Xamarin.Forms and I am using Microcharts to create a bar chart.

I am trying to make a bar chart display the number of books entered this week on each day - from Monday to Sunday.

However, when the user views the page on a Sunday, the bar chart displays only the count on Sunday because it is showing the following week for days Mon-Sat.

Instead, the bar chart should display the data from Monday to Sunday this week.

var days = Enum.GetValues(typeof(DayOfWeek)).OfType<DayOfWeek>().OrderBy(day => day < DayOfWeek.Monday);
var dailyBookCounts =  new Dictionary<string, int>();
foreach (var day in days)
{
    var specificDayAtMidnight = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)day);
    var bookCount = App.Database.GetDailyCount(specificDayAtMidnight);
    dailyBookCounts.Add(day.ToString("G"), bookCount);
}

var entries = new List<ChartEntry>();
foreach (var (nameOfTheDay, bookCountOfTheDay) in dailyBookCounts)
{
    entries.Add(new ChartEntry(bookCountOfTheDay)
    {
        Label = nameOfTheDay,
        ValueLabel = bookCountOfTheDay.ToString(),
        Color = SKColor.Parse("#004daa")
    });
}

chartView.Chart = new BarChart
{
    Entries = entries, 
    LabelTextSize = 32f, 
    LabelOrientation = Orientation.Horizontal, 
    ValueLabelOrientation = Orientation.Horizontal, 
    Margin = 20
};

Database.cs:

public int GetDailyCount(DateTime day)
{
     var dayAfterCurrentDay = day.AddDays(1); 
     return database.ExecuteScalar<int>("SELECT COUNT(*) FROM Book WHERE bookSaveTime> ? AND bookSaveTime< ?;", day, dayAfterCurrentDay);   
}

How can I change this so that the bar chart displays the data from Monday - Sunday of this current week (as opposed to displaying the following weeks' data when the page is viewed on a Sunday)?

Upvotes: 1

Views: 204

Answers (1)

Jason
Jason

Reputation: 89179

you are not correctly calculating the days for the current week. You can use the extension method from this question to do this

// get the first day of current week, starting Monday at 12:00AM
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday);

for (var d = 0; d < 7; d++)
{
  var specificDayAtMidnight = dt.AddDays(d);
  var bookCount = App.Database.GetDailyCount(specificDayAtMidnight);
  dailyBookCounts.Add(specificDayAtMidnight.ToString("G"), bookCount);
}

Upvotes: 1

Related Questions