How to transform a date into a string format with no signs in DateTime?

4

Examples:

string data = "08072013";
string hora = "1515";

Is there a specific method for this type of format? I tried to use Convert.ToDateTime() , DateTime.Parse , etc. and everyone returned an exception. I'm currently doing the following:

StringBuilder strBuilder = new StringBuilder();
strBuilder.Append(data).Insert(2, "/").Insert(5, "/");
strBuilder.Append(" " + hora).Insert(13, ":");
DateTime dateTime = new DateTime();
dateTime = Convert.ToDateTime(strBuilder.ToString());
    
asked by anonymous 01.07.2014 / 22:43

3 answers

7

Use DateTime.ParseExact

There you would find yourself

 string data = "08072013";
 string hora = "1515";
 data = data + hora;
 DateTime ParseData = DateTime.ParseExact(data, "ddMMyyyyHHmm", CultureInfo.InvariantCulture);
    
01.07.2014 / 22:50
3

If you want you can create an extension method with the following nomenclature:

Create a class like this with static and this referring to a DateTime

public static class Methods
{
    public static DateTime ToDateTime(this DateTime _DateTime, string data, string hora)
    {
        try
        {
            return DateTime.Parse(string.Format("{0}/{1}/{2} {3}:{4}",
            data.Substring(0, 2),
            data.Substring(2, 2),
            data.Substring(4, 4),
            hora.Substring(0, 2),
            hora.Substring(2, 2)));
        }
        catch (FormatException ex)
        {
            throw ex;
        } 

    }
}

And use like this:

DateTime date = DateTime.Now.Date.ToDateTime("08072013", "1515");
Ideone Ideone

    
01.07.2014 / 22:51
1
DateTime dateTime = new DateTime(Convert.ToInt32(data.Substring(4, 4), 
                             Convert.ToInt32(data.Substring(2, 2),
                             Convert.ToInt32(data.Substring(0, 2), 
                             Convert.ToInt32(hora.Substring(0, 2), 
                             Convert.ToInt32(hora.Substring(2, 2));
    
01.07.2014 / 22:49