Datetime parsing, but dt changes day from 8th to 7th?

DateTime dt = DateTime.Parse (value)

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

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

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

EDIT: OP code posted as 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";
    }
}
+3
source share
5 answers

My gut says there is a typo in the code. Probably missing a task.

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

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


Based on your editing, I feel your code will be better, but this 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"; 
    }  
}
+3
source

. , :

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

, , .

UPDATE:
, - , :
, , . ?
if, DateTime. - GetFieldValueAsText DateTime. value .
, , , field.GetFieldValueAsText(value) , . , ?

+3

A DateTime , . , DateTime , :

var display = DateTime.Now.ToShortDateString()
+2

A data type DateTimestores both date and time. Unable to change this.

If you want to change the way the date is displayed when it is displayed, simply format it to display only the date. For example, use dt.ToString("D");or dt.ToShortDateString();.

+1
source

The DateTime structure is a point in time, usually expressed as the date and time of the day.

If you want only part of the time, you can choose dt.ToShortTimeString ();

+1
source

All Articles