SPUtility.DateParse !♥ seconds: SPUtility.DateParse removes the time component if you parse a date that incudes seconds!??!

Okay here’s another baffling API bug:

If you parse a date using SPUtility.ParseDate(web, “11/29/2009 13:37:12”, SPDateFormat.DateTime, false) it will return you a date object without parsing the time!

Remove the seconds SPUtility.ParseDate(web, “11/29/2009 13:37”, SPDateFormat.DateTime, false) and we are good to go. Full program listing of bug follows:

using System;
using System.Collections.Generic;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

public class SPUtilityParseDateTest
{
	public static void RunSnippet()
	{
		using (SPSite site = new SPSite("http://localhost"))
		{
			SPWeb web = site.RootWeb;			
			DateTime parsedDate = SPUtility.ParseDate(web, "11/29/2009 3:37:12 AM", SPDateFormat.DateTime, false);				
			WL(parsedDate.ToString());
				
			parsedDate = SPUtility.ParseDate(web, "11/29/2009 3:37 AM", SPDateFormat.DateTime, false);				
			WL(parsedDate.ToString());
			
		}
	}
		
	#region Helper methods
	
	public static void Main()
	{
		try
		{
			RunSnippet();
		}
		catch (Exception e)
		{
			string error = string.Format("---\nThe following error occurred while executing the snippet:\n{0}\n---", e.ToString());
			Console.WriteLine(error);
		}
		finally
		{
			Console.Write("Press any key to continue...");
			Console.ReadKey();
		}
	}

	private static void WL(object text, params object[] args)
	{
		Console.WriteLine(text.ToString(), args);	
	}
	
	private static void RL()
	{
		Console.ReadLine();	
	}
	
	private static void Break() 
	{
		System.Diagnostics.Debugger.Break();
	}

	#endregion
}

The above code assumes you have US regional settings on your root web.

Advertisements
Tagged , , ,

One thought on “SPUtility.DateParse !♥ seconds: SPUtility.DateParse removes the time component if you parse a date that incudes seconds!??!

  1. Zarko says:

    I had the same problem as I was parsing the value from the SP column with the current datetime object. However, when I set the value from sp column to 12 pm, I get an exception, which says my string is not well formated. An alternative I have used is to parse the string value with the sajt culture. SPWeb object has Locale property: DateTime.Parse(myString, web.Locale).

    Regards

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: