Batteredburrito
Batteredburrito

Reputation: 589

UWP/C# Date Storage in a Variable

Now, ive bumped into so many different responses to the usage of Date in C# Ranging from using:

DateTime.Parse
Date.Now

etc. There seems to me a huge amount of ways to use the time date funtion. What i need to do is Read the Day, Month and Year from say today (assuming Date.Now?) and store these values individually so that they can be referenced throughout the entire budget.

The way i was looking at doing this was by having the DateTimeStorage Class in its own Classes Folder. That way, i can reference it at any point throughout the entire project right?

The issue i have bumped into is that i get an error immediately with the following two lines within the class:

class DateTimeStorage
{
    String stringDate;
    DateTime dateValue = DateTime.Parse(stringDate);       
}

According to this, stringDate has an error

a field initialiser cannot reference the non-static field

Now, i was going to close the Class by storing the string values like below:

class DateTimeStorage
{
    String stringDate;
    DateTime dateValue = DateTime.Parse(stringDate); 

     String day = datevalue.Day.ToString();
//etc
}

This doesnt work either, "dateValue does not exist in the current context"

Now, im completely stumped and not sure how best to approach this. There are so many different ways ive seen to do dates. Its hard to know if any of them work the way i need them to.

Would anyone have any suggestions? I need to store the variables as strings as they are going to be used through the entire project to populate fields etc.

Any help would be hugely appreciated

Upvotes: 0

Views: 51

Answers (1)

JSteward
JSteward

Reputation: 7091

What about a static class to store the current date. You could modify this such that the date is able to be updated from elsewhere in the code but this is the simplest approach that initializes the date to Now on program start up.

using System;

namespace ClassLibrary3
{
    public static class StaticDate
    {
        static StaticDate()
        {
            //Initialize Date
            var date = DateTime.Now;
            Year = date.Year;
            Month = date.Month;
            Day = date.Day;
        }

        public static readonly int Year;
        public static readonly int Month;
        public static readonly int Day;
    }

    public class SomeOtherClass
    {
        public void MethodThatNeedsDate()
        {
            var year = StaticDate.Year;
            var day = StaticDate.Day;
        }
    }
}

Upvotes: 1

Related Questions