Pass string to DateTime and take DateTime date only.Now [Updated]

1

When creating a product object that has a DateTime field that field filled it with a DateTime.Now that data is saved in a txt as 03/09/2018 08:42:18 p.m and trying to get the data again with a DateTime.Parse(corte[2]) I get that no se puede reconocer la cadena como un comando date time valido also probre with

string format = "dd/MM/yyyy hh:mm:ss tt";
DateTime.ParseExact(corte[2], format, CultureInfo.InvariantCulture)

Thanks to a user I started to search if corte[2] was taking the value well and I was not taking it well, since I use it to cut a line with split(':') had not realized that I was separating the time and it took a bad date, since I used it to separate fields like name, code.

My second doubt is that in DateTime.Now I do not keep the time if not just the date.

    
asked by Marcel Salazar 04.09.2018 в 03:22
source

3 answers

2

Very good, as you have been told you can use DateTime.Now.Date but if you notice this it returns the date correctly and the time 0:00:00 . If you want to print the date without the time you can use the following:

var dateTime = DateTime.Now.Date;
MessageBox.Show(dateTime.ToShortDateString());

If you want to save only the date in a DataTime object you should use DateTime.Now.Date but remember that when you print the date you should use the ToShortDateString() function so that the time does not appear as 0:00 : 00

I hope it serves you.

    
answered by 04.09.2018 / 08:01
source
2

If you want to take only the date of a DateTime variable you can call its property "Date".

Something like that

var date = DateTime.Now.Date;
    
answered by 04.09.2018 в 05:34
1

Perform the following test

public static void Main()
{
    string fechaString = "03/09/2018 08:42:18 pm";
    DateTime fecha = DateTime.Parse(fechaString);

    Console.WriteLine("fecha: {0}", fecha);
}

As you will see this if you can convert, just remove the point at "p.m"

    
answered by 04.09.2018 в 03:53