Wednesday, April 6, 2011

Convert datetime?

i try to write some code:

Firstly there is a textbox. if you write 13 in textbox, it equals 13.02.2009 (datetime)

Secondly if datetime.now equals 15.02.2009 , you write 13 in textbox, a function return 13.03.2009.

Help me thanks...

From stackoverflow
  • For the second time: go get a book.

    DateTime whichday(int day)
    {
     DateTime today = DateTime.Today;
    
     if(today.Day > day)
      return new DateTime(today.Year, today.Month, day).AddMonth(1);
    
     return new DateTime(today.Year, today.Month, day);
    }
    
    Rowland Shaw : what if the day is 29 (in February)?
    Gerrie Schenck : You can't use AddMonth... ykaratoprak don't want to use math (check his comment) :)
    Phsika : Gerrie Schenck you don2t understand well. i f i say math, i don't like +,-,% , so you can C# special property like addmounth
  • public static DateTime GetDate(int day)
    {
        int month = 0;
        if (day >= DateTime.Now.Day) {month = DateTime.Now.Month;}
        else {month = (DateTime.Now.AddMonths(1).Month);}
        DateTime date = new DateTime(DateTime.Now.Year, month, day);
        return date;
    }
    
    Anton Gogolev : What if DateTime.Now.Month == 12?
    Canavar : yeap, you're right
  • Please try this code and what I mean. Thanks ScarletGarden. Maybe Natrium will learn something about my level.

     static void Main(string[] args)
            {
    
      DateTime startdate=Convert.ToDateTime("15.02.2009");
                int[] frequency ={ 16 }; 
    
                startdate = startdate.AddDays(1 - startdate.Day)
                     .AddDays(frequency[0] -  1)
                     .AddMonths((startdate.Day > frequency[0]) ?1:0);
                Console.Write(startdate.ToString());
                Console.ReadKey();}
    

    For month 15th result is 16.02.2009 but for month 11th result is 11.03.2009 because frequency[0] > startdate is outofdate.

0 comments:

Post a Comment