Format a string with time

Asked

Viewed 2,918 times

3

I’m trying to format a string that already has date and time, but this string just gotta get the time I’m trying this way but it doesn’t work:

Recovering from Data Base.

string dtSolicitacao = String.IsNullOrEmpty(Convert.ToString(drv.Row["dtSolicitacao"])) ? "--" : Convert.ToString(drv.Row["dtSolicitacao"]);

And here trying to format only with the hour:

string IdentNomeHorario = "";
        IdentNomeHorario += "</br>Nome: " + Apelido;
        if (dtSolicitacao != "--")
            IdentNomeHorario += " " + String.Format("{0:HH:MM:ss}", dtSolicitacao);
  • What doesn’t work? How time is coming from the base?

  • The base time is coming so 27/08/215 09:06:33, I wanted to format just to show the time 09:06:33 without the day.

3 answers

3


You can use the method DateTime.Parse():

String.Format("{0:HH:MM:ss}", DateTime.Parse(dtSolicitacao))

Or else, in a more dirty way you can give a .Split() on date:

IdentNomeHorario += " " + dtSolicitacao.Split(' ')[1];

But I recommend the first option, of course.

  • Thanks Dontvotemedown for the help.

  • @krispim needing we are ae.

3

You can do this which is more elegant:

DateTime.Parse(dtSolicitacao).TimeOfDay

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Anyway, make sure that the date format is correct. If you are not, it is best to treat this before making an exception. Therefore the correct solution is not to record a date as string in the database. This is bad practice in several senses.

There is a way that might please you more if the date might be wrong:

DateTime horario2;
if (DateTime.TryParse(dtSolicitacao), DateTimeStyles.None, out horario2)) {
    Console.WriteLine(horario2.TimeOfDay);
} else {
    Console.WriteLine("deu erro"); //trate como achar melhor aqui, este foi só um exemplo
}

Documentation.

  • Good placement on the field type in the database.

0

Look, the object of Type DateTime has the property TimeOfDay that returns a TimeSpan with the current schedule.

So it is interesting to convert the value of the cell dtSolicitacao for a DateTime, like the dtSolicitacao is not required, so we will use the DateTime.TryParse to avoid conversion errors:

var cultureInfo= new CultureInfo("pt-BR");
var strSolicitacao = drv.Row["dtSolicitacao"].Value as String;      
var dtSolicitacao = default(DateTime);
DateTime.TryParse(strSolicitacao, cultureInfo, DateTimeStyles.None, out dtSolicitacao);

now to assemble the IdentNomeHorario, let’s test whether dtSolicitacao has a value and then we will use a string String.Format.

var strHorario = dtSolicitacao != default(DateTime) ? dtSolicitacao.TimeOfDay.ToString() : String.Empty;
var IdentNomeHorario = String.Format("</br>Nome: {0} {1}", Apelido, strHorario);

Browser other questions tagged

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