-4

Sorry For the very basic answer but I'm struggling trying to find a way to convert a DateTime.Today to an int. This Doesn't work but you can assume what im going for

int CurrentDay = DateTime.Today;

Thanks For any Help at all.

Josh Elton
  • 17
  • 1
  • 1
  • 2
    What do you expect `CurrentDay` to be? The day of month or day of year or day since `DateTime.MinValue`? – René Vogt Aug 31 '16 at 08:11
  • It depends, but maybe you want `int oaDayCount = (int)(DateTime.Today.ToOADate());`. Another possibility is `int totalDayCount = (int)(DateTime.Today.Ticks / TimeSpan.TicksPerDay);`. – Jeppe Stig Nielsen Aug 31 '16 at 08:24

4 Answers4

9

Using Day Property:

int currentDay = DateTime.Today.Day;

Gets the day of the month represented by this instance.

You can also use DayOfWeek and DayOfYear when you need them.

Zein Makki
  • 29,485
  • 6
  • 52
  • 63
0

You have to convert Today to String, remove the dots and convert to int.

You could try:

int currentday = Convert.ToInt32(DateTime.Today.ToShortDateString().Replace(".", ""));

You may use long if you add Time.

This question has been asked at Stack Overflow a few times in the past. For example, look at this answer:

Click here

Then, look at the right column in this question/answer for more linked and related questions/answers.

You can search in Stack Overflow (search field in upper right corner) with keywords

[c#] convert datetime to int

A Google search would lead to solutions of your question, too. For example, use keywords

c# convert datetime to int

I know this should be a comment, but I cannot do it because of my rep, sorry.

Community
  • 1
  • 1
user319785
  • 31
  • 1
  • 4
0

You can store your dateTime as a number with this solution, only that you have to store it as an Int64 if you need also the time component:

[TestMethod]
public void DateTimeToInt64()
{
   long ticks = DateTime.Today.Ticks;

   DateTime dateTimeFromTicks = new DateTime().AddTicks(ticks);

   Assert.AreEqual(dateTimeFromTicks, DateTime.Today);
}

For the case you don't need the time part of the date:

[TestMethod]
public void DateTimeToInt32()
{
    var dateTimePattern = "yyyyMMdd";
    int numericDateTime = Convert.ToInt32(DateTime.Today.ToString(dateTimePattern));

    DateTime dateTimeFromInt32 = DateTime.ParseExact(numericDateTime.ToString(), dateTimePattern, CultureInfo.InvariantCulture);

    Assert.AreEqual(dateTimeFromInt32, DateTime.Today);
}

Or using OADate :

[TestMethod]
public void DateTimeToOADate()
{
    double oADate = DateTime.Today.ToOADate();

    DateTime dateTimeFromOAdate = DateTime.FromOADate(oADate);

    Assert.AreEqual(dateTimeFromOAdate, DateTime.Today);
}
Nina
  • 1,035
  • 12
  • 17
0

If anyone is still looking to do this, I believe he wanted the day of the week as a zero based integer. Sunday = 0 to Saturday = 6

public static DateTime _dt = DateTime.Now;
public static int _day = (int)_dt.DayOfWeek;

Today is Monday so _day == 1

Dave_P
  • 174
  • 2
  • 16