Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parsing datetime but dt is changing the day from 8th to 7th?

DateTime dt = DateTime.Parse(value)

Where my value = {3/8/2011 12:00:00 AM}

but dt is showing dt = {3/7/2011 12:00:00 AM}

Please shed some light as I am about to pull my hair.

EDIT: Code OP posted as a comment:

foreach (SPField field in contentType.Fields)
{
    string fValue;
    object value = spitem[field.Id];
    if (value is DateTime)
    {
        DateTime dateField = DateTime.Parse(field.GetFieldValueAsHtml(value));
        DateTime dt = DateTime.Parse(field.GetFieldValueAsText(value), CultureInfo.GetCultureInfo("en-US"));
        fValue = dt.ToShortDateString();
        lblMetaData.Text += field + ": " + fValue + "\r\n";
    }
    else
    {
        fValue = field.GetFieldValueForEdit(value);
        lblMetaData.Text += field + ": " + fValue + "\r\n";
    }
}
like image 879
Madhu Landh Chodh Avatar asked Dec 15 '25 13:12

Madhu Landh Chodh


2 Answers

My gut tells me there is a typo in the code. There is probably a missing an assignment.

DateTime dt = DateTime.Parse("3/7/2011 12:00:00 AM");
....
DateTime.Parse("3/8/2011 12:00:00 AM"); //Parse's return is being ignored
....
dt is still {3/7/2011 12:00:00 AM}

Make sure the call to DateTime.Parse("3/8/2011 12:00:00 AM"); is being assigned to dt.


Based on your edit I feel like your code would be better like this, however the posted code should still work.

foreach (SPField field in contentType.Fields) 
{ 
    string fValue;
    object value = spitem[field.Id]; 

    if (value is DateTime) 
    { 
        DateTime dt = (DateTime)value;
        fValue = dt.ToShortDateString(); 
        lblMetaData.Text += field + ": " + fValue + "\r\n";
    } 
    else 
    {         
        fValue = field.GetFieldValueForEdit(value); 
        lblMetaData.Text += field + ": " + fValue + "\r\n"; 
    }  
}
like image 153
Bob Avatar answered Dec 17 '25 02:12

Bob


I can't reproduce your problem. The following code works for me, no change in the day part:

DateTime dt = DateTime.Parse("3/8/2011 12:00:00 AM", CultureInfo.GetCultureInfo("en-US")); 
Assert.AreEqual(new DateTime(2011, 3, 8), dt);

Please try to post actual code that reproduces your problem.

UPDATE:
Now that you posted some code, I can say the following:
Your code doesn't seem to make sense. Why?
Because your code will only execute the if clause, if value is a DateTime. But in that case, you first somehow convert it to a text with GetFieldValueAsText and parse that text back into a DateTime. Just use the value directly.
Anyhow, even with that strange code, it should work, if field.GetFieldValueAsText(value) would work correctly, which I doubt it does. Did you check that it indeed returns the correct string?

like image 25
Daniel Hilgarth Avatar answered Dec 17 '25 03:12

Daniel Hilgarth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!