How to transform a date into a string format without signals in Datetime?

Asked

Viewed 1,352 times

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 all returned me an Exception. I am currently doing it as follows:

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());
  • 3

    Do not use a StringBuilder so little. http://answall.com/questions/7734/performance-string-concatenado-ou-todo-na-mesma-linha/21973#21973

  • @bigown is that I’m going to run this up in thousands of records.

  • 1

    And what is the advantage in thousands of records? Did you measure and see that concatenating is slower? Or did you surmise?

  • 1

    To help you I made a quick test of the solutions presented, including yours. There is a solution that even works and I had to arrange to test and even so the people voted for it, has solution that is the same or slower than yours. I created one with concat, I knew she wouldn’t do well but she’s simpler and wasn’t slower than using the StringBuilder. Ideally testing on a stable machine, a dotNetFiddle server is obviously unstable. Remembering that the StringBuilder generates a violent pressure on the GC. The concat no. https://dotnetfiddle.net/6hPvJ4

  • The only thing I’m saying is that in generic cases for simple things it’s better to use a simple concatenation because the performance will be essentially the same as the StringBuilder. In simpler things, the performance will be better. But it is obvious that for your specific case the solution you correctly accepted is shot the best.

  • And if you’re so concerned about performance you could unify the last two lines. You’re creating an instance of DateTime that you don’t use anywhere just to overwrite with another instance right on the next line. Just create with what you want. Do not create something that will then be discarded without use. The Convert.ToDateTime(strBuilder.ToString()) already returns a DateTime.

  • @bigown I found that in cases like this, StringBuilder would do better, since (in my confused knowledge) a string is immutable... and the code I put in the question was just a test I was doing and not the final code. Can you explain or give me some link about what is this violent pressure that the StringBuilder You do it at GC? And it’s not that I care so much about performance, the system I’m making is for internal use, man, but I think it’s always nice to try to do it the right way... Thanks for the tips.

  • 1

    I understood, I’m just showing you that what it seems is not always true. In comments will not give to explain the pressure in GC. I also think it’s to do the best way, so I’m giving you the tips. I realize that you care about this, just need to understand some things not to worry about the wrong target. Do you think I knew that the accepted answer was the fastest? I didn’t know, I was suspicious. It gave me curiosity and I decided to test to learn this. It could be worse. See how easy it is to fool yourself with performance http://answall.com/a/21941/101

  • 1

    I didn’t resist, I’ll try to summarize. violent was an exaggeration. Concat simples tem performance O(1) and SB tem O(log N), is much worse, but of course complex Concat is even worse, is O(N). SB decreases the amount of allocations but not everything possible. In the background the Concat that you can make decay to the SB when it is not so simple. But it has the advantage of being simpler to put it in the code of q the SB. SB should only be used when the additions to one same string occurs in a loop. It’s a little more complicated than this but that’s what you gave in a comment. http://answall.com/a/16063/101

  • 1

    SB can be used as O(1) if you know the total size of string resulting end, so in your case you can optimize your code to be O(1) even using SB. But the code will be even more complex than using a simple concatenation. Code simplicity is usually preferable even considering that the time spent on this conversion will be tiny in the whole that will be spent to access the records you are talking about. The summary I’ve tried to tell you since the beginning is don’t make your code more complicated to gain something close to 0.1% performance in total processing.

  • I understood more or less... Would you have some article on the subject to pass me? Just out of curiosity...

  • 1

    Nothing I can remember, I’m a little tied up these days. There are the links I gave you that help. About performance, never assume, always test. And don’t make premature optimization, don’t complicate the code for a very small and worse gain, which is not necessary. Even the test can give the wrong answer, it is not always easy to understand what to test. I did not take the test, at the time I did not think about this case, but the answer that has try/catch for example, it may be extremely slower if the dates are invalid. No exaggeration, can be orders of magnitude slower. But you have to test.

Show 7 more comments

3 answers

7


Uses the DateTime.ParseExact

There in your case would be

 string data = "08072013";
 string hora = "1515";
 data = data + hora;
 DateTime ParseData = DateTime.ParseExact(data, "ddMMyyyyHHmm", CultureInfo.InvariantCulture);
  • 1

    Dude, here there is no overload with two parameters in this method. It is asking for a third parameter (Iformatprovider). I am using . NET 4.0, that would be it?

  • I did it without testing, but the idea is this one, updated.

  • What is this last parameter?

  • 1

    @Caiquec. Here is more information about the latest parameter http://msdn.microsoft.com/pt-br/library/system.globalization.cultureinfo.invariantculture(v=vs.110). aspx I put so for him to pick up indepedente of the culture that is set. PS: I tested and worked right.

  • 4

    @Caiquec. The last parameter is where you tell the method which culture you will use. This is because it is possible to use, as the second parameter, certain strings that are ready formats (i.e.: "g") - in this case, it is the third parameter that defines how the parser will handle each character. CultureInfo.InvariantCulture is a "standard" culture of the framework for cases where no real culture applies.

  • 1

    Perfect answer, congratulations!!!

  • @Diegovieira I used this only today... in the conversion of hours between 0 and 12, ok, from there, I have formats from 13 to 24 and in these return me a argumentexception... Would it be because of Culture? Resolve to change to Brazilian/ptbr?

  • 1

    If I’m not mistaken, HH is in 24 hours, it has nothing to do with culture.

  • @Thank you Diegovieira! That was the problem, I don’t know why, but here I was with the tiny H’s. Vlw by the light!

Show 4 more comments

3

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

Create a class like this one with Static and this referencing a type of 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 wear it like this:

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

Example: Ideone

  • 3

    I know it solves the problem. But in a code review, it would make a lot of people exclaim WTF!.

  • 4

    i still think more wtf you send a date in this format, that is. Let’s say that it is a simpler code to compensate the Gambia of the date.

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));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.