Solved

C# DateTime from Month and Year

Posted on 2015-02-23
4
182 Views
Last Modified: 2015-02-24
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
Comment
Question by:sbornstein2
  • 2
4 Comments
 
LVL 12

Assisted Solution

by:FarWest
FarWest earned 150 total points
ID: 40626795
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
 
LVL 50

Accepted Solution

by:
Gustav Brock earned 350 total points
ID: 40627677
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
 

Author Closing Comment

by:sbornstein2
ID: 40628228
ah very clever it is.   Did not know it could parse a month and year like that.  Thanks
0
 
LVL 50

Expert Comment

by:Gustav Brock
ID: 40628238
You are welcome!
.Net is magic.

/gustav
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…

680 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question