Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi!

Im a fairly new programmer and i like to experiment and create my own applications.

Im trying to convert dates to a specific form.
Many people can type/write dates diffirently and im trying to write a code that converts all these dates to a specific form. Example:

You can write todays date as follows:

26/6 -2012(day/month/year)
120626(year/month/day)
12-06-26(year/month/day with "-")
26 june 2012(day/month/year)

No matter how this is written i want to write a code that converts it to:
2012/06/26(year/month/day)

So far i have come up with this syntax that handels the month names:

C#
class Program
{
    static void Main(string[] args)
    {
        string strDate;
        Console.WriteLine("Please enter a date: ");
        strDate = Console.ReadLine();
        MonthsInArray month = new MonthsInArray(strDate);



        Console.ReadLine();
    }
}

And the other class:
C#
public MonthsInArray(string month)
{
    string strMonth;
    strMonth = month;
    Hashtable MyHash = new Hashtable();
    MyHash.Add("01","Januari");
    MyHash.Add("02","Februari");
    MyHash.Add("03","March");
    MyHash.Add("04","April");
    MyHash.Add("05","May");
    MyHash.Add("06","June");
    MyHash.Add("07","July");
    MyHash.Add("08","August");
    MyHash.Add("09","September");
    MyHash.Add("10","Oktober");
    MyHash.Add("11","November");
    MyHash.Add("12","December");


    foreach (string strMonthIndex in MyHash.Keys)
    {
        string strMonthName = (string)MyHash[strMonthIndex];

        if (strMonth == strMonthName)
        {
            Console.WriteLine(strMonthIndex);
        }

    }


After this im kind of stuck, since the date is to be saved in ONE string variable no matter how it is written. Although this is what i would like it to be like but i do welcome other soloutions ASLONG as a soloution with the ONE variable soloution is presented.

Im really thankfull for any help that i can get here!

Regards
Peter
Posted
Updated 26-Jun-12 11:13am
v3
Comments
Sergey Alexandrovich Kryukov 26-Jun-12 17:42pm    
Why would you not simply read MSDN on the topic? Your MyHash data is pointless; this data is already available in .NET Framework.
--SA
Clifford Nelson 26-Jun-12 17:46pm    
There are too many ways to write dates that can be confused. If at least the month is written out or abbreviated (no numbers), you have some hope of being able to distinguish the dates. However it is common to write dates in the form mm-dd-yy and dd-mm-yy. You can only hope to make it out. This means that you con sometimes only guess.

Why don't you use
C#
DateTime
Try to parse the passed string according to the expected formats and store it as a DateTime, then you can output in your preferred format.
 
Share this answer
 
Comments
wizardzz 27-Jun-12 10:36am    
Why the f*** was this downvoted? It is literally what SAK ended up recommending after my post, except I didn't feel the need to explain it in detail, AS IT IS SO SIMPLE I assumed the OP could figure out how to use a standard .NET object that is fully documented in msdn. I pointed him in the right direction, which last I checked, is a valid answer.
Please see my comment to the question. Everything is already done for you, just look at the type System.DateTime, http://msdn.microsoft.com/en-us/library/system.datetime.aspx[^].

To get a time value from string, you can use one of parse methods, please read about them. To write it in a string in required format, use one of System.DateTime.ToString methods. The particular format is defined by culture (see ToString(IFormatProvider), ToString(String, IFormatProvider), and CultureInfo which implements IFormatProvider) and/or string format. For formats, please see:
http://msdn.microsoft.com/en-us/library/az4se3k1.aspx[^] (standard format strings),
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx[^] (custom format strings).

[EDIT]

To respond to the follow-up discussion. First, you code sample is wrong. More importantly, your problem cannot be solved in general case. Here is what you should use, basically:
C#
string dateString = "03-04-2012";
System.DateTime dateMonthDayYear = System.DateTime.ParseExact(
    dateString,
    new string[] { "MM-dd-yyyy" },
    null, System.Globalization.DateTimeStyles.None);
System.DateTime dateDayMonthYear = System.DateTime.ParseExact(
    dateString,
    new string[] { "dd-MM-yyyy" },
    null, System.Globalization.DateTimeStyles.None);
System.DateTime dateAmbiguous = System.DateTime.ParseExact(
    dateString, new string[] { "dd-MM-yyyy", "MM-dd-yyyy" },
    null, System.Globalization.DateTimeStyles.None);

First two interpretation of the date string "03-04-2012" are unambiguous, by the last one is ambiguous, because, without a priory assumptions, you cannot tell if "03" is a month or a day. But, if your input would be "29-04-2012" or "04-29-2012", one of the first to calls to ParseExact will throw an exception (use TryParse, TryParseExact to work without exceptions, if you want), but the third call will give you an unambiguous result; all three cases will work this way just because "29" cannot be a month number.

This way, you cannot allow the user to enter date in arbitrary format without specification of parsing rules, no matter how hard you try.

Practically, you can used fixed custom or standard format, or, as a perfect solution, some UI with date-time picker like System.Windows.Forms.DateTimePicker, http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.aspx[^].

Enjoy,
—SA
 
Share this answer
 
v5
Comments
Espen Harlinn 26-Jun-12 18:19pm    
5'ed!
Sergey Alexandrovich Kryukov 26-Jun-12 18:29pm    
Thank you, Espen.
--SA
Maciej Los 26-Jun-12 18:48pm    
Well explained, my 5!
Sergey Alexandrovich Kryukov 26-Jun-12 18:57pm    
Thank you, Maciej.
--SA
PeterC#Prog 27-Jun-12 4:39am    
Alright ive gotten a better understanding of this.

I normaly don´t read MSN since i find it confusing most of the time.

I gave it a shot and tried the following:

string strDate = "dd-MM-yy";(this is the format i want the date to be entered)
Console.Write("Enter a date: ");
strDate=Console.ReadLine();

DateTime date1 = DateTime.Parse(strDate,
System.Globalization.CultureInfo.InvariantCulture); (My pc is set to show the date accordingly: YY-MM-DD and thats how i want the date i enter in strDate to be converted to)
Console.WriteLine(date1.ToString());

I get the following error:
The string was not recognized as a valid DateTime.

As i said before i find MSDN very confusing and i have probably misunderstood how Datetime works and would appreciate some code with comments!

thanks alot for the fast response, i thought it would take at least 24 hours before i would receive an answer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900