Convert string to Time

Asked

Viewed 4,168 times

5

I got a column in the database that gets a guy varchar which corresponds the hours on my app ("HH:MM").

I need to convert this string to a type TIME and then concatenate with a type DateTime. Someone has done something similar?

  • It is not a good practice to have a given text where it would be a data of the type Time. If you can normalize this data everything for team would be better ...

  • Have you tried something like concatenating the date with Time first and then converting? For example: var conc = "01/01/2010" + " 02:03" hence then: var dt = new DateTime(conc);

4 answers

4

I would turn the string to TimeSpan and then add to DateTime that already exists:

var dateTime = new DateTime(2014, 04, 14);
var finalDateTime = dateTime + TimeSpan.Parse("12:10");

If you are using LINQ to Entities, you could try to bring the data from the already converted database to TimeSpan using the method: EntityFunctions.CreateTime:

var itens = db.MeuTipo.Select(x => EntityFunctions.CreateTime(
                                       Convert.ToInt32(x.CampoVarChar.Substring(0, 2)),
                                       Convert.ToInt32(x.CampoVarChar.Substring(3, 2)),
                                       null)).ToList();

I just can’t test it right now.

2

Problems converting string to Datetime

First, you need to keep in mind that there are several ways a Datetime/Timespan presents itself, you can check this out here. So it is not very safe for you to convert a string to Datetime/Timespan without proper care, as this can be interfered with by the regional settings that the server has, since the default Datetime/Timespan format is defined by this.

A safe solution

The method Tryparseexact allows us to define one or more formats for Timespan and Datetime, in addition to ignoring the regional language settings and let us know if there was success or not! This all ensures much more robust code.

Note: I’m not thinking about defining Cultureinfo on the Web.Config, I just thought of a code-level solution.

The Code

    private static void Main(string[] args)
    {
        DateTime dataJaConhecida = DateTime.Now.Date;

        TimeSpan horasConvertidas;
        if (!TimeSpan.TryParseExact("03:12", @"h\:m", CultureInfo.InvariantCulture, out horasConvertidas))
        {
            Console.WriteLine("Horas no formato inválido");
        }
        else
        {

            Console.WriteLine(dataJaConhecida.ToString("dd/MM/yyyy HH:mm"));

            dataJaConhecida += horasConvertidas;

            Console.WriteLine(dataJaConhecida.ToString("dd/MM/yyyy HH:mm"));
        }

        Console.ReadKey();

    }
  • Hi friends, good afternoon! Thank you very much for the answers, they have helped me a lot, since I am new in the area. Regarding the danger of regional model I took care to put jquery plugins, javascript rules and validations on the server. Thank you

0

I was able to solve the case with the following solution:

var horaRetorno = retornoVeiculo.HoraDaChegada.Split(':')[0];
var minRetorno = retornoVeiculo.HoraDaChegada.Split(':')[1];
var tR = retornoVeiculo.DataDaChegada.AddHours(double.Parse(horaR));
tR = tR.AddMinutes(double.Parse(minR));

This way the string containing the time is broken into 2 parts and at the end the two are incorporated into the field Time of the kind Datetime.

0

To do this routine you could simply

DateTime Data = DateTime.Parse("01/01/1999" + " " + "03:03:03");

Browser other questions tagged

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