Format a string with time

3

I'm trying to format a string that already has date and time, but this string just has to get the time I'm trying in this way more does not work:

>

Recovering from the database.

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

And here trying to format with just the time:

string IdentNomeHorario = "";
        IdentNomeHorario += "</br>Nome: " + Apelido;
        if (dtSolicitacao != "--")
            IdentNomeHorario += " " + String.Format("{0:HH:MM:ss}", dtSolicitacao);
    
asked by anonymous 27.08.2015 / 14:01

3 answers

3

You can use the DateTime.Parse() :

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

Or, in a nutshell, you can give a .Split() on date:

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

But I recommend the first option, of course.

    
27.08.2015 / 14:11
3

You can do this which is more elegant:

DateTime.Parse(dtSolicitacao).TimeOfDay

See working on dotNetFiddle .

In any case, make sure the date format is correct. If not, it is best to treat this before giving an exception. So the correct solution is not to write a date as string in the database. This is a bad practice in many ways.

It has a form that may please you more if the date may 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 .

    
27.08.2015 / 14:24
0

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

So it's interesting to convert the value of cell dtSolicitacao to DateTime , since dtSolicitacao is not required, so we'll use 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 mount IdentNomeHorario , let's test if dtSolicitacao has a value and then we'll mount the string using String.Format .

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