Get the first day of the current week

Posted February 24th, 2011 in .NET, Extension Methods by admin

Here is a quick way to get the first day of the current week.

If you are happy with sunday as the first day of the week, then you can simply do this :


 public static DateTime FirstDayOfWeek(this DateTime date)
 {
            return DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek);
 }

But if you want that the first day of the week matches your culture (eg: the belgian week starts on monday), you have to take care of the culture’s DateTime format.

So the method will change a bit :


public static DateTime FirstDayOfWeek(this DateTime date)
{
     return DateTime.Today.AddDays(-((int)DateTime.Today.DayOfWeek - (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek));
}
Usage :

    DateTime FirstDayOfWeek = DateTime.Today.FirstDayOfWeek();

or

 DateTime FirstDayOfWeek = DateTime.Now.FirstDayOfWeek();

Get the parent Folder for a SPListItem

Posted February 18th, 2010 in Extension Methods, Reminders, Sharepoint by Sam Beauvois

To retrieve the parent folder

my extension method


public static SPFolder GetParentFolder(this SPListItem spListItem)

{

if (spListItem == null)

return null;

SPFile spFile = spListItem.Web.GetFile(spListItem.Url);

if (spFile == null)

return null;

return spFile.ParentFolder;

}

Use


SPFolder parentFolder = sPListItem.GetParentFolder();

if (parentFolder != null)

{

// do some stuffs..

}
public static SPFolder GetParentFolder(this SPListItem spListItem)
{
if (spListItem == null)
return null;
SPFile spFile = spListItem.Web.GetFile(spListItem.Url);
if (spFile == null)
return null;
return spFile.ParentFolder;
}[/csharp]