Reference > Functions > Date and Time
DatePart
- 2005
- 2008
- 2012
- 2014
- 2016
- 2017
- 2019
- 2022
- 2005, 2008, 2012, 2014, 2016, 2017, 2019, 2022
DatePart Date and Time Function
Use the DatePart
function to return the specified part of a date.
Syntax
db.fx.DatePart({DATEPART}, {expression})
Arguments
- DATEPART
- – The part of `expression` to extract. `DATEPART` is an enumeration (in the `DbExpression.MsSql.Expression` namespace).
- expression
- – The date value to extract `DATEPART` from.
Returns
int or int?
(based on nullability of `start_date_expression` and `end_date_expression`)
Examples
Select Statement
Select the year of ship date.
IEnumerable<int?> result = db.SelectMany(
db.fx.DatePart(DateParts.Year, dbo.Purchase.ShipDate)
)
.From(dbo.Purchase)
.Execute();
Where Clause
Select all product ids of products that shipped on Friday.
IEnumerable<int> purchase_ids = db.SelectMany(
dbo.Purchase.Id
)
.From(dbo.Purchase)
.Where(db.fx.DatePart(DateParts.Weekday, dbo.Purchase.ShipDate) == 6)
.Execute();
Order By Clause
Select all purchases ordered by the week the product shipped.
IEnumerable<Purchase> result = db.SelectMany<Purchase>()
.From(dbo.Purchase)
.OrderBy(db.fx.DatePart(DateParts.Week, dbo.Purchase.ShipDate))
.Execute();
Group By Clause
Select product information grouped by product category type and the week the product was added to the system.
IEnumerable<dynamic> results = db.SelectMany(
dbo.Product.ProductCategoryType,
db.fx.DatePart(DateParts.Week, dbo.Product.DateCreated).As("Week")
)
.From(dbo.Product)
.GroupBy(
dbo.Product.ProductCategoryType,
db.fx.DatePart(DateParts.Week, dbo.Product.DateCreated)
)
.Execute();
Having Clause
Select purchase values grouped by payment method type that shipped the first week of the year.
IEnumerable<dynamic> results = db.SelectMany(
dbo.Purchase.PaymentMethodType,
dbo.Purchase.ShipDate
)
.From(dbo.Purchase)
.GroupBy(
dbo.Purchase.PaymentMethodType,
dbo.Purchase.ShipDate
)
.Having(
db.fx.DatePart(DateParts.Week, dbo.Purchase.ShipDate) == 1
)
.Execute();