Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 231
  • Last Modified:

C# DateTime from Month and Year

Hello all,

I have the following,  Month Abbreviation such as Jan and Year such as 2015 in a string "Jan 2015".   I need to take that and get the 1st and last day of that month into two datetime variables.  

I got the month abbreviation using:

DateTimeFormatInfo mfi = new DateTimeFormatInfo();
mfi.GetAbbreviatedMonthName(1) as an example.

I guess I need to parse the numeric and string portion to do this?   So in the above case Jan 2015 I would want two datetime variables as:

DateTime startDate = 1/12015
DateTime endDate = 1/31/2015
0
sbornstein2
Asked:
sbornstein2
  • 2
2 Solutions
 
FarWestCommented:
check this code
      static void Main(string[] args)
        {
            string mmmyyyy = Console.ReadLine();// enter date ex feb 2015
            DateTime sdate = Convert.ToDateTime("01 " + mmmyyyy);
            DateTime edate = sdate.AddMonths(1);
            edate = edate.AddDays(-1);
            Console.WriteLine("Start Date is " + sdate.ToString("MM/dd/yyyy"));
            Console.WriteLine("Start Date is " + edate.ToString("MM/dd/yyyy"));
            Console.ReadKey();

        }

Open in new window

0
 
Gustav BrockCIOCommented:
You should use the very clever method Parse for this:

String monthYear = "Jan 2015";
DateTime startDate = DateTime.Parse(monthYear);
DateTime endDate = startDate.AddMonths(1).AddDays(-1);  

/gustav
0
 
sbornstein2Author Commented:
ah very clever it is.   Did not know it could parse a month and year like that.  Thanks
0
 
Gustav BrockCIOCommented:
You are welcome!
.Net is magic.

/gustav
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now