Перейти к содержимому

Как из datetime взять только дату без времени

  • автор:

Get only the Date without Time from DateTime

i came across a situation that, i need to get only the Date out from DateTime .

i am having a DateTime? StartDate property ( Nullable ) used to hold the date value

var d = Convert.ToDateTime(StartDate).Date;

but its returning me d as eg. 6/22/2006 12:00:00AM

after doing var d = Convert.ToDateTime(StartDate).Date.ToString(«d»);

i’m able to get d as 6/22/2006 ..but i dont want to convert my DateTime? to String

is their any way to get only the Date without using the ToString(«d») ?

5 Answers 5

Use the Date property to get the Date component of DateTime instance:

With this approach, Date property will return the date at midnight. So the time part will be 00:00:00 in this case.

There are couple of alternate ways to get the just the Date part, but the return type of it will be a string:

1.) Using .ToString(string? format) where format can be standard or custom format string

2.) Using .ToShortDateString() to return a culture sensitive date string

Saket Kumar's user avatar

try this: string x = DateTime.Now.ToShortDateString() .

this will get the date dd/mm/yy given to the string x.

I think you question is sort of. moot.

You ask for a date without a time, but get a DateTime , which has both. I really don’t think that should be a problem in most cases though:

If you create a DateTime with a certain date, and compare it to another date, and both of these have their time set to midnight, your comparisons will be valid and correct. Eg:

Comparing and sorting these will work as you expect, and so will the following:

In other words, you should be perfectly fine just pretending like the time-part does not exist.

Also, as you touched upon yourself in the OP, you can use the property Date if you want to make sure to avoid any time-component:

Как извлечь только дату из DateTime (без времени)

Как преобразовать ее в String с откинутым временем ("12.12.2012") ?

Как вывести только в поле GridView только дату (без времени)?
Всем добрый день! У меня есть GridView: <asp:GridView runat="server".

Как вывести только дату без времени через модель и хранимую процедуру?
Подскажите, пожалуйста, как в таблице вывести только дату? У меня в БД тип данных стоит date, но.

Вывести только дату без времени
Есть база данных в Microsoft Access и там хранятся данные, есть поля с датой. В базе данных я.

Как сгрупировать по datetime без учёта времени
Здравствуйте есть таблица `event` id | date | price date — храниться в формате.

TablePlus

MS SQL Server — How to get Date only from the datetime value?

September 1, 2018

To get the current date and time:

And we have a datetime value: 2018-09-01 11:50:05.627

From the datetime value above, you want to extract the date value only and hide the time value. There are several ways to do that:

1. Use CONVERT to VARCHAR:

In this case, date only, you we are gonna run this query:

It returns 2018/09/01 for my test.

The style we used just now is 111, which is yyyy/mm/dd. There are many other style you can choose from. Here are some common types:

Style How it’s displayed
101 mm/dd/yyyy
102 yyyy.mm.dd
103 dd/mm/yyyy
104 dd.mm.yyyy
105 dd-mm-yyyy
110 mm-dd-yyyy
111 yyyy/mm/dd
106 dd mon yyyy
107 Mon dd, yyyy

Because each type generates a different length, so you should define the right varchar length then.

2. You can also convert to date:

It will return the current date value along with starting value for time. For example, the result for my case is:

For older version than SQL Server 2008, you should use this instead:

And it returns the same result.

3. Use CAST

For the example above, you can use:

Or you can cast it to varchar:

Need a good GUI Tool for MS SQL Server? Try TablePlus, a modern, native tool for multiple databases including SQL Server, MySQL, PostgreSQL, SQLite, etc. And it’s free to use for as long as you need it to.

Remove Time from Datetime in Python

To remove the time from a datetime object in Python, convert the datetime to a date using date().

You can also use strftime() to create a string from a datetime object without the time.

When working in Python, many times we need to create variables which represent dates and times. When creating and displaying values related to dates, sometimes we need to display the current date.

With Python, we can easily remove the time from a datetime variable.

To get rid of the time, we just need to convert the datetime to a date. To do so, use the datetime date() function.

Below is a simple example of how to get remove the time from a datetime in Python.

Using strfttime to Remove the Time from Datetime in Python

The Python strftime() function is very useful when working with date and datetime variables. strftime() accepts a string representing the format of a date and returns the date as a string in the given format.

We can use strftime() to easily remove the time from datetime variables.

For example, if you want to print out the date in the format “YYYY-MM-DD”, we pass “%Y-%m-%d” to strfttime() and no time is printed.

Below is a simple Python example of how to print the date without time using strftime().

Hopefully this article has been useful for you to learn how to use Python to remove the time from datetime variables.

Other Articles You'll Also Like:

  • 1. Multiple Condition While Loops in Python
  • 2. pandas to_pickle – Write DataFrame to Pickle File
  • 3. Python Check if Object Has Attribute
  • 4. How to Save and Use Styles from Existing Word File With python-docx
  • 5. Using Python to Check If Variable is Not None
  • 6. How to Check if Variable Exists in Python
  • 7. Are Tuples Mutable in Python? No, Tuples are not Mutable
  • 8. Python Add Months to Datetime Variable Using relativedelta() Function
  • 9. Using Python to Count Number of Lines in String
  • 10. Using Python to Replace Multiple Spaces with One Space in String

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *