How can I get today's date from a string and not the full value of it?

0

I have an application which I need to export several values. In one of them I have a string that returns a date with time included "2/8/2017 10:26:35 AM".

What I need is to extract this string but only validating the day the code is executed.

Example:

If the string has "2/8/2017 10:26:35 AM" I need the value of "2/8/2017".

I have tried to use Contains (DateTime.Today) but it does not work for me.

How can I achieve this?

Greetings

    
asked by A arancibia 08.02.2017 в 18:31
source

4 answers

2

If you have a string like this:

string fecha_de_prueba = "2/8/2017 10:26:35 AM";

Of which you only want to obtain the day, month and year, you can choose:

Separate the value of the string fecha_de_prueba as follows:

string fecha_de_prueba = "2/8/2017 10:26:35 AM";
string fecha_ddmmyyyy = fecha_de_prueba.Split(' ')[0];
// Resultado: 2/8/2017

Or, simplified:

string fecha_de_prueba = "2/8/2017 10:26:35 AM";
fecha_de_prueba = fecha_de_prueba.Split(' ')[0];
// Resultado: 2/8/2017

To compare the dates, you can do the following:

DateTime fecha_actual = DateTime.Today;
// Valor: 08/02/2016 00:00:00

string fecha_de_prueba = "2/8/2017 10:26:35 AM";
DateTime fecha_a_comparar = DateTime.Parse(fecha_de_prueba.Split(' ')[0]);
// Valor: 02/08/2017 00:00:00

// Aquí validas que los días de ambas fechas sean las mismas
// (tal como indicas en tu pregunta).
if (fecha_actual.Day == fecha_a_comparar.Day) {
   // TODO: Ejecutar tu código.
}
    
answered by 08.02.2017 / 18:39
source
0

If you know that after the date there always comes a blank space, then you can use:

string source = "2/8/2017 10:26:35 AM";
var result = source.Split(new Char[] {' '}, 2).First();
    
answered by 08.02.2017 в 18:39
0

Try as follows

'string fecha_de_prueba = "2/8/2017 10:26:35 AM";
 string pattern = "M/d/yyyy h:mm:ss tt"
 DateTime date = DateTime.ParseExact(
        fecha_de_prueba, 
        pattern, 
        CultureInfo.InvariantCulture);
 string newstrDate = date.ToString("M/d/yyyy");

There is also a TryParseExact that validates before in case the date may not have the format

    
answered by 08.02.2017 в 18:49
0

Just to expand the answers, in my opinion when working with dates is always better to use the type dedicated to it, or DateTime .

In this case, what I would do would be to compare the property Date of DateTime , which would result in something like this:

DateTime dt1 = DateTime.Parse("9/2/2017 10:26:35 AM", CultureInfo.CurrentCulture);
if (DateTime.Now.Date==dt1.Date)
{

}
    
answered by 09.02.2017 в 08:58