Text with date formatting in excel

Excel for Microsoft 365 Excel for Microsoft 365 for Mac Excel 2021 Excel 2021 for Mac Excel 2019 Excel 2019 for Mac Excel 2016 Excel 2016 for Mac Excel 2013 Excel 2010 Excel 2007 Excel for Mac 2011 More…Less

Suppose you want to create a grammatically correct sentence from several columns of data for a mass mailing or format dates with text without affecting formulas that use those dates. To combine text with a date or time, use the TEXT function and the & (ampersand) operator.

Example

Examples to show how formulas can combine text with date and time values

The TEXT function requires two arguments (that is, items between its parentheses). The first argument is a value, such as a date or a number. This value is converted to a text value. The second argument, format_text, is a special string that Excel recognizes and uses to display the converted text value in a format that you specify. In the second and third examples, the dates in B3 and B4 are converted to text and then is displayed in two different formats: “d-mmm-yyyy” (resulting in June 4, 2010) and “mmmm d, yyyy.” (resulting in Jun-07- 2010).

Need more help?

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

Working with dates is a common task for many Excel users.

And sometimes, you can come across dates that are formatted as text (or look like dates but are not in the acceptable date formats, so Excel treat them as text strings).

Since dates are stored as numbers in the backend in Excel, it allows you to format dates in different ways as well as use them in calculations.

But when a date is stored as a text string in Excel, you won’t be able to use it in calculations or format it like a date.

In this tutorial, I will show you how to convert text into dates in Excel.

I will cover various scenarios where you may encounter a date that has either been formatted as text or is entered as a text string (and Excel doesn’t recognize that it’s a date).

Regular Date vs Text Date in Excel

Before I get into the methods on how to convert text to date in Excel, let me first explain what’s the difference between a date that is an acceptable format in Excel, and a date that is in the text format.

As I mentioned earlier, dates are stored as numbers in the back end in Excel, which makes it possible for us to use them in calculations just like numbers.

This also makes it possible for us to format dates and show it in different ways, which cannot be done when the date is entered as a text string or formatted as a text.

To give you an example, 01-Jan-2023 is an acceptable date format in Excel and if you enter this in a cell, it would be shown as a date, but it would be stored as 44927 in the backend (where 44927 is the number corresponding to the date 01-Jan-2023).

However, if you enter 01.Jan.2023, it would be entered as a text string because this is not an acceptable date format. This also means that you cannot use this in calculations because this has not been stored as a number in the back end

Below I have the table where I show the difference between an acceptable date format and a date in text format or entered as a text string.

Date Stored as Number Dates Stored as Text
Since these are numbers in the backend, these dates would be aligned to the left by default Since these are text, these would be aligned to the right
These can be used in calculations If dates are entered as a text string in Excel, you won’t be able to use this in formulas. However, if dates are formatted as text, then you can convert them back to numbers/dates, and then use them in formulas.

You can change the format to show these in other acceptable date formats (such as MM-DD-YYYY or DD-MM-YYYY or show only the month name or only the month and year)Since these are text, you cannot change the formatWhen you select cells containing the dates, you would be able to see Sum or Average in the status barSince these are text strings, you would only see the count value in the status bar

Now let’s look at some of the methods you can use to convert text to dates in Excel

Convert Text to Date in Excel (with acceptable Date Formats)

First, we’ll look at scenarios where you have dates that are considered acceptable date format in Excel but are formatted as text in the cells.

For example, 01-Jan-2023 is an acceptable date format, and in case it has been formatted as text, you will be able to use the methods shown in this section to convert it back to date.

However, if a date is entered in a format that is not an accepted date format (such as 01.Jan.2023 or 8th Jan 2023), you will have to use methods covered later in this tutorial.

Using the DATEVALUE Function

Often, when you download your data from a database or you copy your data from a web page, you would notice that the dates have been formatted as text.

If your date is in the acceptable date format but has been formatted as text, you can easily convert it into the corresponding serial number by using the DATEVALUE function.

And once you have the number, you can easily format it as a date.

Below I have a data set where I have dates in column A that have been formatted as text and I want to convert these back to regular dates.

Date Dataset VALUE

This can be done using the below DATEVAUE formula:

=DATEVALUE(A2)

Copy this formula to all the cells in column B.

DATEVALUE formula result

When you use this formula, it gives you a numeric value, which corresponds to the date in cell A2.

So while we have got the text date converted into a number, we still need to format it so that it shows up as a date in the cell.

Below are the steps to format these numbers in column B to date:

  1. Select the cells that contain DATEVALUE results
  2. Click the Home tab
Click the Home tab
  1. In the Numbers group, click on the formatting drop-down
  2. Select the ‘Short date’ or ‘Long date’ format
Select Short or Long date format

The above steps would convert the text that you have in column A into serial numbers using the DATEVALUE function, and then these are formatted to show up as dates.

Date formatted as long date

In case you need more control over how the dates are formatted, you can also use the Format Cells dialog box, which has a lot more date formatting options, as well as the option to create your own date format.

Also read: How to Change Date Format In Excel?

Using the VALUE Function

While the DATEVALUE function is built specifically to deal with dates that have been formatted as text, there is also a VALUE function that can deal with dates as well as non-dates.

VALUE takes any number that has been formatted as text and converts it back into numbers.

Below I have a data set where I have dates in column A that are in the text format, and I want to convert these back into regular dates.

Date Dataset VALUE

Below is the VALUE formula that will do this for me:

=VALUE(A2)

Copy this formula to all the cells in column B.

VALUE function to change text to date

And if you see the result as numeric values and not dates, you can format the cells to show these in dates using the below steps:

  1. Select the cells that contain VALUE formula results
  2. Click the Home tab
  3. In the Numbers group, click on the formatting drop-down
  4. Select the Short date or Long date format
Select Long or Short date format

Using Mathematical Operators (Add, Multiple, Double Minus, Division)

If you have a date in the format that Excel understands (even if it is in the text format), you will be able to use it in simple arithmetic calculations (such as addition or subtraction or multiplication or division).

We can use simple arithmetic calculations to convert the date that we have in the text format back into numeric format.

All you need to make sure is that you don’t end up changing the date in the calculation (which won’t happen if you add zero to the date or multiply the date by 1).

Below I have a data set where I have the dates in the text format in column A (but note that these are the dates that Excel would have considered as proper dates had they not been in the text format).

Date Dataset VALUE

And here are some simple arithmetic calculations you can use in the adjacent column to get the numeric value of the date.

=A2+0

or

=A2*1

or

=A2/1

or

=--A2

You can use any of the above formulas and it would give you a numeric value in column B as shown below.

Add 0 to get the numeric value

Note that we have the numeric value of the date in column A comma we can convert these back into date format.

Below are the steps to convert these numeric values into dates:

  1. Select the cells in column B that have the numeric value
  2. Click the Home tab
  3. In the number group, click on the drop-down
  4. Select the date format that you want to apply to the selected cells

In case you want to customize the date format further, select the cells in column B and then use the keyboard shortcut Control + 1 to open the Format Cells dialog box. Here you will get more date format options and you can also create your own custom date format if you want.

Using Paste Special

As explained in the previous method, you can convert a date that is formatted as text back into a numeric value by adding a zero to it.

While I’ve used a formula and got the result in a separate column in the above method, you can also do the same thing using the Paste Special dialog box.

Below I have a data set where I have the dates in the text format in column A and I want to convert these back to dates:

Date Dataset VALUE

Below are the steps to convert dates in text format back into dates using the Paste Special technique:

  1. Copy any blank cell in the worksheet
  2. Select the dates in column A
  3. Right-click on the selection and then click on Paste Special option. This will open the Paste Special dialog box
Click on Paste Special
  1. Select the ‘Values’ option in the ‘Paste’ category
  2. In the ‘Operation’ category, select the ‘Add’ option
Select Values and Add in Paste Special
  1. Click Ok

The above steps would instantly convert all the dates in column A into numeric values.

Dates changed to numbers

Now you can select these cells and change the format to show these numbers as dates.

Format the date - short or long

How does this work?

When I copy a cell and then use paste special to add that cell to the dates in column A it’s essentially adding zero to these dates.

This addition does not change the numeric value of the date but it does convert the date value which is formatted as text into a numeric value that represents that date in the back end of Excel.

Also read: How to Multiply in Excel Using Paste Special

Convert Text to Date (with Format Not Recognized as Dates)

In all the examples covered above, I’ve shown you how to convert a date that is in the text format back into a date.

But so far, all our dates were in a format that Excel actually recognizes as a proper date.

It’s just that they have been formatted as text, so all we had to do was change the format back to date.

In this section, I’m going to show you some techniques that you can use when you have dates that are not recognized by Excel proper dates.

Such datasets often need more work, as we need to manipulate the data and convert it into proper date formats

By Changing the Delimiters in the Date

When there are dots or spaces instead of forward-slash or hyphens in a date, Excel would consider it as a text value as this is not an acceptable date format in Excel.

Below I have data set where I have the dates in column A where there are dots in between the day, month, and year number.

Dates with dots as delimiters

If you try to use the DATEVALUE or the VALUE function on this data, it will give you a value error (as Excel does not know how to convert this text string into a numeric value).

DATEVALUE function gives error

So the only way to convert this text value into data is by replacing the dot and changing the date into a proper date that Excel can recognize as a date.

Let me show you three different ways you can use to change the delimiters in the date in column A so that it can be used as a proper date in Excel.

Find and Replace

With Find and Replace, we can replace the dots in the date with a forward slash or hyphen/dash so that it will become a proper date format.

Below I have dates in column A that have dots as delimiters and I want to replace them with a forward slash or hyphen.

Dates with dots as delimiters

Here are the steps to do this:

  1. Select the cells in column A that have the date
  2. Click the Home tab
Click the Home tab
  1. In the Editing group, click on Find & Select
  2. Click on the ‘Replace’ option. This will open the Find and Replace dialog box
Click on Replace
  1. In the ‘Find what’ field in the dialogue box, enter . (dot)
  2. In the ‘Replace with’ field, enter – dash
Find what and replace with in Find and Replace dialog box
  1. Click on ‘Replace All’

The above steps would instantly change the dots in the dates into dashes, making the text values in column A into dates. Note that the dates also aligns to the right (while it was aligned to the left when it has dots instead of dashes).

Dates converted from text to dates

Pro Tip: You can use the keyboard shortcut Control + H to open the ‘Find and Replace’ dialog box

Using Text to Columns

Another quick way to convert dates that are in text format into proper dates is by using the Text to Columns option.

Below I have a dataset where I have dates in column A that have dots as the delimiters and I want to convert these into regular dates that are recognizable by Excel.

Date dataset for text to columns

Below are the steps to do this using Text to Columns:

  1. Select the cells in column A that have the dates
  2. Click the ‘Data’ tab
Click the Data tab
  1. In the ‘Data Tools’ group, click on the ‘Text to Columns’ option
Click on Text to Columns
  1. In Step 1 of the Convert Text to Columns Wizard, select Delimited and then click on Next
Step 1 of Text to Columns
  1. In Step 2, make sure none of the delimiter option is selected, and then click on Next
Step 2 of Text to Columns
  1. In Step 3, select the Date option and specify the destination cell (I would use $B$2 in this example). If you do not specify the destination cell, the data in the column would be overwritten
Step 3 of Text to Columns
  1. Click on the Finish button

The above steps would instantly give you the dates in column B

Text to Columns result date

It’s possible that the dates that you get in Column B are not in the format that you want.

So once you have the result, you can change the format by selecting the cells in Column B, holding the Control key, and pressing the 1 key. This will open the Format Cells dialog box where you can change the format of the dates.

SUBSTITUTE Function

You can also use the SUBSTITUTE function to replace the dots or dashes or any other delimiter with a forward slash or dash.

While the result of the SUBSTITUTE formula would be a text string, since it would be in an acceptable date format, we would be able to use DATEVALUE function to convert it into the numeric value of the corresponding date.

And once we have the numeric value, we can then format the cells to show the date in any format we want.

Below I have the data set where I have dates in column A that have dots as the delimiters, and I want to convert these into proper dates.

Date dataset for text to columns

Build the formula that would give us the numeric value that represents the proper date:

=DATEVALUE(SUBSTITUTE(A2,".","-"))

Enter this formula in cell B2 and then copy it for all the other cells.

SUBSTITUTE function to change delimiter in date in Excel

Once you have the results in column B, follow the below steps to convert these numbers back into dates:

  1. Select the cells in Column B that have the dates
  2. Click the Home tab
  3. In the Number group, click on the Format drop-down
  4. Select the ‘Short Date’ option

In case you want the dates to be shown in any other format, open the format cells dialog box and then choose from the multiple inbuild date formats or create your own custom date format.

Note that in the above formula, I had dots in the dates that I wanted to replace with dashes. In case you have any other delimiter (such as space), you need use that delimiter instead of the dot in the formula.

Convert Two Digit Year Text Date to Proper Date By Using Error Checking

Sometimes you may get a data set where the year is represented by two digits instead of the four digits in the date.

For example, instead of 01-Jan-2023, it would be 01-Jan-23

Thankfully, it only takes a click to get this sorted.

Below I have a data set in column A where I have the dates with two-digit year values and I want to convert these into proper date formats.

Date in two year digit format

Here are the steps to do that:

  1. Select all the cells in column A that have the two-digit year date
  2. Click on the error-checking icon at the top right of the selection (it’s a yellow triangle icon)
Click on the yellow error triangle icon
  1. Click on ‘Convert XX to 20XX’ option
Select convert XX to 20XX option

The above steps would change the dates and convert the two-digit year value to a four-digit year value.

Note that you can only use this if all the dates in your data set are of the same format (19XX or 20XX). In case there is a mix (for example in the case of date of birth), you will not be able to use this method

Using TEXT formulas

Sometimes you may get dates that have some additional text in the same cell.

For example, you can get a date where it includes the day name (such as Saturday, 08 Oct 2022) or a suffix after the day value (such as 8th October 2023 or 2nd October 2023).

In these cases, you first need to use some text formulas to clean the data and remove these unwanted text strings, and then try and convert these dates into their corresponding serial number (which can be done using the DATEVALUE function).

Let me show you a couple of common examples and how you can do this using simple text formulas:

When You Have Day Name in the Date

Below I have a data set where I have the day name before the date in column A, and I want to convert these dates in column A into proper date format.

Date with day name

Here is the formula that will do this for me:

=DATEVALUE(RIGHT(A2,LEN(A2)-FIND(" ",A2)))

Enter this formula in cell B2 and then copy it for all the cells in column B.

DAY name removed with formula

In the above data set, the day name is always followed by a comma and a space character.

Since this is the same in all the cells in the data set, I have used the above formula to first identify the position of the first space character (using the FIND function).

Once I know the position of the first space character, I used the RIGHT function to extract everything which is to the right of that space character.

And since the result of the RIGHT function is still a text string, I’ve used the DATEVALUE function to get the serial number of the date.

Once you have the serial number of the date, you can format the cell to show it in the short or long date format (your option is available in the Home tab in the formatting drop-down)

When You have Suffix After the Day Value in the Date

Below are the data set where I have a suffix (such as ‘th’, ‘rd’, ‘nd’, ‘st’) after the day value.

Dates with suffix

Because of this, the date is considered as a text string in Excel, and to convert this date in the text format back into the date format, I will have to remove the suffix from these cells.

Below is the formula that will do this for me:

DATEVALUE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A2,"th",""),"st",""),"rd",""),"nd",""))

Enter this formula in cell B2 and then copy it for all the cells in column B.

formula to remove suffix from date

In the above formula, I have used the SUBSTITUTE function to remove each of these suffix values and replace these with blanks.

Since there are four such values (th, st, rd, nd), I had to use the SUBSTITUTE function four times.

The result of one SUBSTITUTE function is fed into another SUBSTITUTE function so that in the end we get the result where any of these four suffixes would be removed.

Once the suffixes are removed, we have used the DATEVALUE function to get the serial number of the date so that we can convert it back into the proper date format

Convert 8 Digit Date in MMDDYYYY format to Date

Below I have a data set where I have the dates in the DDMMYYYY format, where there is no space or delimiter between any of the digits.

Date in 8 digit format

Since the above dataset follows a consistent pattern (where the first two digits are always the day value, the next two digits are the month value, and the last four digits are the year value), we can use simple text formulas to extract these digits and specify them as the day, month and year values.

Here is the formula that will do this for me:

=DATE(RIGHT(A2,4),MID(A2,3,2),LEFT(A2,2))

Enter this formula in cell B2 and then copy it for all the cells in column B.

Formula to convert 8 digit to proper date

The above formula uses the RIGHT, MID, and LEFT functions to extract the year, month, and day values respectively,

And then these are used within the DATE function to construct a proper date in Excel.

In this tutorial, I showed you how to convert text to date in Excel using various techniques.

The method you use would depend on whether your date is in a format that Excel would recognize as a proper date or not.

If it is in a proper date format and is being considered as a text string in Excel, you can use formulas such as DATEVALUE or VALUE to get the serial number of the date and then format it to show as a short or long date.

You can also use simple arithmetic operators or Paste Special operation techniques to quickly convert dates that are formatted as text into serial numbers corresponding to that date.

And in case your dates are in a format that is not recognized by Excel a date, you will need to do some text manipulation using simple text formulas or functionalities such as Find and Replace or Text to Columns.

I hope you found this Excel tutorial useful.

Other Excel tutorials you may also like:

  • How to Compare Dates in Excel (Greater/Less Than, Mismatches)
  • Combine Date and Time in Excel (Easy Formula)
  • Convert Date to Text in Excel – Explained with Examples
  • How to Convert Serial Numbers to Dates in Excel
  • Convert Text to Numbers in Excel
  • How to Convert Numbers to Text in Excel

Working with dates in Excel might not be as simple as working with plain numbers and text, and the reason is that Excel’s way of storing and displaying dates is very different.

Moreover, Excel can display the same date in multiple ways (or formats).

The good news though is that it is possible to convert between date formats quite easily.

In this tutorial we will show you three ways to apply the Short Date format to any date in Excel:

  • Using the Number Format menu
  • Using the Format Cells dialog box
  • Using the TEXT function

What are Long Date and Short Date Formats?

One of the formats in which Excel displays dates is the Long date Format.

This format displays the day of the week along with the full month name as shown below:

Date in long form format

Notice the actual date in the formula bar is just 1/1/2021.

However, since the cell is formatted to display the date in Long format, it shows the date in the cell as Friday, January 1, 2021.

The Long Date format might not be the most convenient form to display your date.

It’s too long, so it ends up taking a lot of space and you would need to increase the column width to accommodate the full format.

Moreover, if you see pound symbols “###” in a cell that contains a date, it is usually because the width of the cell is too narrow to display the full date.

This often happens when your cell contains the date in Long format.

A good way to reduce the column size or to handle “###” errors would be to apply the Short Date format to the cells. 

Also read: How to Insert Date in Excel?

Let us look at three ways in which we can apply the Short Date format to a given cell or range of cells in Excel.

We will apply each method to the set of dates shown below:

Dataset with dates in different formats

Notice that each date is displayed in a different format.

For example, the date in the first row is in Long Date format, while the one in the second row is displayed in the form of the serial number that represents the date. 

We are going to apply the Short Date format to all the above dates by the following three methods.

Method 1: Using the Number Format Menu to Apply Short Date Format in Excel

The first method is actually the quickest way to apply the Short Date format to a cell or range of cells.

All you need to do is:

  1. Select the cell or range of cells to which you want to apply the Short Date format.
  2. Click the Home tab from the main menu.
  3. Click on the dropdown arrow in the “Number” group (shown in the image below):
Click home and then the date format drop down
  1. In the dropdown menu that appears, you should see a number of number formatting options. Click on the ‘Short Date’ option.
Select short date from drop down

You should now have the Short Date format applied to all the selected cells as shown below:

Dates converted to short format

In case you don’t see the cell content convert into the short date format, a possible reason could be that the cell has text content (which is not something that Excel considers a date)

Also read: How to Remove Year from Date in Excel?

Method 2: Using the Format Cells Dialog Box to Apply Short Date Format in Excel

This method is a little more versatile as it also lets you customize your Short date according to your requirement.

For example, you can set the components of the date to be separated by hyphens (-), slashes (/) or dots (.).

Here are the steps that you need to follow to apply Short Date format using this method:

  1. Select the cell or range of cells to which you want to apply the Short Date format
  2. Right-click on your selection and select ‘Format Cells’ from the context menu that appears. Alternatively, you can use the CTRL+1 shortcut from your keyboard.
Click on Format cells
  1. This will open the Format Cells dialog box. Select the Number tab.
Click on Number tab
  1. Make sure that the ‘Date’ option is selected from the list under ‘Category’.
Click on the Date option
  1. This will display a number of date formatting options on the right side of the dialog box.
  2. Select the short date format that you want to apply to your dates. For a general Short Date format, you can simply select the option shown below:
Select the date in short format
  1. Click OK to close the Format Cells dialog box.

You should now have the Short Date format applied to your selected cells as shown below:

Date converted to short format

If you need a more customized date format, then you can type in the format that you want in the input box under ‘Type’, after selecting the ‘Custom’ option from the ‘Category’ list (instead of step 4). 

Customizing the short date format

For example, if you type the format “mm-dd-yy” then your date will be formatted to display two-digit month, day, and year numbers separated by hyphens, as shown below:

Date in mm-dd-yy format

Your customized format needs to follow certain rules. For example, to represent the month number without a leading zero, you can use the “m” code.

To display the month number with a leading zero, on the other hand, you can use the “mm” code. Here are some of the codes that you can use:

Code Description Example
m Month number without leading zero 1
mm Month number with leading zero 01
d Day number without leading zero 5
dd Day number with leading zero 05
yy Year with last 2 digits only 21
yyyy Full-year with 4 digits 2021

You can combine the above codes to create your required short-date format.

Here are a few example date formats that are commonly used:

Format Example
dd-mm-yy 13-01-21
mm/dd/yyyy 01/13/2021
mm-dd-yy 01-13-21
m.d.yy 1.13.21
m/dd/yy 1/13/21
Also read: How to Apply Long Date Format in Excel?

Method 3: Using the TEXT Function to Apply Short Date Format in Excel

The first two methods apply the Short Date format to the original cell(s).

If, however, you want to keep the original date(s) in the Long format as is and display the Short format in a separate cell, then you can use the TEXT function.

The TEXT function lets you convert dates to different text formats.

It takes a DATE value and lets you format it according to a given format code.

The syntax for the TEXT function is:

= TEXT (date_input, date_format_code)

In the above formula syntax:

  • date_input is the date value or a reference to a cell containing a date that you want to apply the Short Date format to.
  • date_format_code is the format code that specifies how you want the resulting date to look.

These format codes are the same as the codes discussed in Method 2.

The TEXT function applies this format code to the specified date_input and it returns a text string in the given format.

For example, the following formula takes the date provided in cell A2 and returns the date “1/1/21”:

=TEXT(A2,”m/d/yy”)

Note: Always remember to enclose the format_code in quotes.

Insert this formula in cell B2 (of our sample dataset) and copy it down to the rest of the cells in column B.

Here’s how the result that you should get:

TEXT formula to show date in mdyy format

The only issue with the TEXT function is that the date that is returned is actually a string and not a DATE value.

That is why you see the results aligned to the left side of the cells instead of the right. So you cannot perform subsequent operations with the result (i.e., you can’t use it in calculations that use date as the input).

The benefit of using the TEXT function to get the date in the short format is that you can add any text string before or after the date.

For example, if you want to show the result as Date: 01/01/2021, you can use the below formula:

 ="Date: "&TEXT(A2,”mm/dd/yy”) 

In the above formula, I have appended “Date: ” before the TEXT function, which will make sure that the result I get would have the desired text before the date followed by the date in the specified format.

In this tutorial, we showed you three ways in which you can apply the Short Date format in Excel.

The first method is the quickest and the most commonly used. The second method is more versatile as it lets you customize the short date to your required format.

The third method is not used all that often, but you can use this method if you don’t want to make changes directly to the original cells.

We tried to make this tutorial simple and easy to follow.

We hope it was helpful.

Other Excel tutorials you may also like:

  • How to Apply Accounting Number Format in Excel
  • How to Apply Comma Style in Excel (3 Easy Ways)
  • Why are Dates Shown as Hashtags in Excel? Easy Fix!
  • How to Convert Date to Day of Week in Excel (3 Easy Ways)
  • How to Convert Date to Month and Year in Excel (3 Easy Ways)
  • How to Sort by Date in Excel (Single Column & Multiple Columns)
  • How to Change Date and Time to Date in Excel
  • How to Calculate the Number of Months Between Two Dates in Excel?
  • How To Combine Date and Time in Excel
  • Apply Currency Format in Excel (Shortcut)

What is the Date Format in Excel?

In Excel, a date is displayed according to the format selected by the user. One can choose from the different formats available or create a customized format according to the requirement. The default date format is specified in the “Control Panel” of the system. However, it is possible to change these default settings.

For example, the date 01/01/2021 corresponds to the format dd/mm/yyyy. If the format is changed to d-mmm-yyyy, the date becomes 1-Jan-2021.

We can change the date format in Excel either from the “Number Format” of the “Home” tab or the “Format Cells” option of the context menu.

In Excel for Windows, 1900 is the default date system. Whereas, in Excel for Mac, 1904 is the default date system. Both these systems store the dates as consecutive numbers having a difference of 1. These numbers are known as serial values or serial numbers. The reason dates are stored as serial numbers is to facilitate calculations.

In the 1900 date system, the first date that Excel recognizes is January 1, 1900. This date is stored as the number 1 in Excel. Consequently, the number 2 represents January 2, 1900. The last date recognized by Excel is December 31, 9999. It is represented by the serial number 2958465. Date before 1900 or after 9999 is identified as a text value by Excel.

Dates are stored only as positive integers in the 1900 date system. However, to display negative numbers as negative dates, one needs to switch to the 1904 date system.

In the 1904 date system, 0 represents January 1, 1904, and -1 means January -2, 1904. The number 1 represents January 2, 1904. The last date recognized by Excel (in the 1904 date system) is December 31, 9999, represented by the serial number 2957003.

In this article, we follow the 1900 date system.

Table of contents
  • What is theDate Format in Excel?
    • Code of Date Format in Excel
    • How to Change Date Format in Excel?
      • Example #1–Apply Default Format of Long Date in Excel
      • Example #2–Change the Date Excel Format Using “Custom” Option
      • Example #3–Apply Different Types of Customized Date Formats in Excel
      • Example #4–Convert Text Values Representing Dates to Actual Dates
      • Example #5–Change the Date Format Using “Find and Replace” Box
    • Frequently Asked Questions
    • Recommended Articles

Code of Date Format in Excel

A code (like dd-mm-yyyy) is a representation of a day (d), month (m), and year (y). We can change the appearance of the date by changing the specified code.

The different codes, their explanation, and output (for days, months, and years) have been presented in the following images.

Notations for a Day

excel date format example 4.1

Notations for a Month

excel date format example 4.2

Notations for a Year

excel date format example 4.3

How to Change Date Format in Excel?

Here we look at some of the date format examples in Excel and how to change them.

Example #1–Apply Default Format of Long Date in Excel

The following image shows a number in cell A1. We want to know the date represented by this number. The output should be in the long date format of Excel.

Excel Date Format Step 1

The steps to know the date represented by the number in cell A1 are listed as follows:

  1. We must first select cell A1. Then, from the “Home” tab, click the “Number Format” drop-down appearing in the “Number” section. Next, select “Long Date,” shown in the following image.

    Excel Date Format Step 2

  2. The output is shown in the following image. The long date format displayed is dd mmmm yyyy. Hence, the number 1 represents the date 01 January 1900 in the long date format.
    Note: The short and long dates appear as set in the “Control Panel.” Click “Clock, Language, and Region” in the “Control Panel” to change these default date formats. After that, click “Change date, time, or number formats.” Make the desired changes and click “OK.”

    Excel Date Format Step 3

    Likewise, had there been 2 in cell A1, the long date format would have been 02 January 1900. The number 3 would have been displayed as 03 January 1900 in the long date format.

    Note: To switch to the 1904 date system, we must select “Advanced” from the “Options” of the “File” tab. Under “When calculating this workbook,” select “use 1904 date system” and click “OK.”

You can download this Change Date Format Excel Template here – Change Date Format Excel Template

Example #2–Change the Date Excel Format Using “Custom” Option

The following image shows some dates in the range A1:A6. These dates are in the format dd-mm-yyyy. We want to change their format to dd-mmmm-yyyy.

For instance, the date in cell A1 should appear as 25-February-2018. We may use the “Custom” option of the “Format Cells” dialog box.

change Date Format Step 1

The steps to change the date format in Excel are listed as follows:

Step 1: We need to select all the dates of the range A1:A6. The same is shown in the following image.

change Date Format Step 2

Step 2: We must right-click the selection and choose “Format Cells” from the context menu. Alternatively, we may also press the keys “Ctrl+1” together.

change Date Format Step 3

Step 3: The “Format Cells” window opens, as shown in the following image.  

Note: The default short date and long date formats are marked with an asterisk (*) in the box under “type.” The short date is 3/14/2012 (m/dd/yyyy), and the long date is Wednesday, March 14, 2012 (dddd, mmmm dd, yyyy).

change Date Format Step 4

Step 4: From the “Number” tab, we need to select “Custom” under “Category.” The categories are shown on the left side of the “Format Cells” window.

change Date Format Step 5

Step 5: Under “Type,” we must insert the required date format. Either type the format (dd-mmmm-yyyy) or select it from the various options displayed in the box below “Type.”

Once the format has been entered, check the preview of the first date (of the range A1:A6) under “Sample.” The same is shown in the following image. Click “OK” in the “Format Cells” window if the date preview looks good.

Note 1: The date under “Sample” is displayed according to the format specified under “Type.”

Note 2: While creating custom date formats, we can use a forward slash (/), hyphen (-), comma (,), space ( ), etc.

excel date format example 2.5

Step 6: The output is shown in the following image. All dates of the range A1:A6 have been converted to the format dd-mmmm-yyyy. However, the Excel formula bar can still see the default date format. This default format corresponds with the short date set in the “Control Panel.”

Example #3–Apply Different Types of Customized Date Formats in Excel

The next image shows certain dates in the range A1:A6. At present, the date format is dd-mm-yyyy.

We want to apply four different formats to these dates. For using each format, the common steps to be performed are given as follows:

  1. First, we must select the range A1:A6.
  2. Then, right-click the selection and choose “Format Cells.”
  3. After that, from the “Number” tab, select “Custom” under “Category.”

Further, under each format, the additional steps to be performed followed by two images are given.

Format 1: dd-mmm-yyyy

  1. In the “Custom” option of the “Number” tab, select the format “dd-mmm-yyyy” under “Type.”
  2. Click “Ok.”

The output is given in the following image. All dates are displayed according to the format dd-mmm-yyyy. The hyphen is the separator between the day, month, and year in this format.

Format 2: dd mmm yyyy

  1. We must select the format “dd mmm yyyy” under “Type” of the “custom” option.
  2. Click “Ok.”

The output is given in the following image. All dates are converted to the format dd mmm yyyy. The space is the only separator between the day, month, and year in this format.

Format 3: ddd mmm yyyy

  1. In the “Custom” option, select the format “ddd mmm yyyy” under “Type.”
  2. Click “Ok.”

The output is given in the following image. The dates are shown in the format ddd mmm yyyy. The day and the month are displayed in their short notations in this format.

Format 4: dddd mmmm yyyy

  1. From the “Custom” option of the “Number” tab, select “dddd mmmm yyyy” under “Type.”
  2. Click “Ok.”

The output is given in the following image. All dates have been converted to the format dddd mmmm yyyy. The date, month, and year are displayed in their respective full forms in this format.

excel date format example 3.8

It must be observed that the date format changes as per the style set by the user. Therefore, the user can select a date format according to their convenience.

Example #4–Convert Text Values Representing Dates to Actual Dates

The following image shows a list of dates in the range A1:A6. At present, these dates are appearing as text values. We want to convert these text values to dates having the format dd-mmm-yyyy.

format as text example 5.1

The steps to convert text values to dates having the given format are listed as follows:

Step 1: First, enter the following formula in cell B1.

“=VALUE(A1)”

Then, press the “Enter” key.

Note 1: The VALUE functionIn Excel, the value function returns the value of a text representing a number. So, if we have a text with the value $5, we can use the value formula to get 5 as a result, so this function gives us the numerical value represented by a text.read more returns the numeric form of a text string that represents a number. In other words, it converts a number looking like the text into an actual number.

Note 2: Instead of the VALUE function, one can also use the DATEVALUE functionThe DATEVALUE function in Excel shows any given date in absolute format. This function takes an argument in the form of date text normally not represented by Excel as a date and converts it into a format that Excel can recognize as a date.read more of Excel. The latter converts a date stored as text to a serial number. This serial number is recognized as a date by Excel.

Step 2: We must select cell B1 and drag the fill handle until cell B6. The output is shown in the following image. All text values (A1:A6) have been converted to numbers (in the range B1:B6).

Ideally, the text string in Excel is left-aligned while the number string is right-aligned. However, we have centrally aligned both the ranges (A1:A6 and B1:B6).

Note: When text strings representing dates have been converted to serial values (or dates), we can use them for performing different calculations like addition, subtraction, and so on.

convert to number example 5.2

Step 3: To view the obtained serial numbers (in column B) as dates, apply the required format. We must select the range B1:B6, right-click and choose “Format Cells.”

In the “Number” tab, select the option “Custom.” Then, under “Type,” enter or choose the format “dd-mmm-yyyy.” The same is shown in the following image.

If the sample date looks alright, click “OK.”

apply format example 5.3

Step 4: The output is shown in the following image. Hence, all text values (of column A) have been converted to valid dates (in column B) having the format dd-mmm-yyyy.

Note: To ensure that a value is recognized as a date by Excel, check for the following signs:

  • The dates are right-aligned as they are numerical values.
  • If two or more dates are selected, the status bar (at the bottom of the worksheet) shows the count, average, numerical count, and sum. In addition, it may display one or more options according to the Excel version.

If a value is a text string, it would be left-aligned, and the status bar will show only the count.

result example 5.4

Often, the Excel date format needs to be changed (from text to dates) when data is downloaded (or copied and pasted) from the web. That is because, in such instances, the dates may not be displayed as numbers.

Example #5–Change the Date Format Using “Find and Replace” Box

The following image shows some text values representing dates in the range A1:A6. The days, months, and numbers have been separated with a backslash. That is because we want to perform the following tasks:

  • Replace all the backslashes () with forwarding slashes (/) by using the “Find and Replace” dialog box.
  • Convert text values representing dates to actual dates.

date data example 6.1

The steps to perform the given tasks are listed as follows:

Step 1: We must press the keys “Ctrl+H” together. Then, the “find and replace” dialog box opens, as shown in the following image.

find & replace example 6.2

Step 2: Type a backslash in the “Find what” box (). In the “Replace with” box, type a forward slash (/).

find & replace example 6.3

Step 3: Next, we must click “Replace All.” Excel shows a message stating the number of replacements it has made. Click “OK” to proceed. The final output is shown in the following image.

Hence, all backslashes have been replaced with forwarding slashes. With this replacement, the text values representing dates have automatically been converted to actual dates by Excel.

Since column A was aligned centrally from the beginning, this alignment is retained even after the values are converted to dates.

Frequently Asked Questions

1. How can the date format in Excel be changed?

The steps to change the date format in Excel are listed as follows:
The steps to change the date format in Excel are listed as follows:

a. Select the cell containing the date. If the date format of a range needs to be changed, select the entire range.
b. Right-click the selection and choose “Format Cells” from the context menu. Alternatively, press the keys “Ctrl+1” together.
c. IIn the “Number” tab, select the option “Date.” Next, select the required date format under “Type.”
d. Check the preview (of the first date of the selected range) under “Sample.” If the preview is good, click “OK.”

The date format of the selected cell or cells (selected in step a) is changed.

Note 1: The required date format may not be available under the “Date” option’s “Type.” If it is not available, select “Custom” as the “category” from the “Number” tab. Then, type the required date format under “Type” and click “OK.”

Note 2: If the selected cell (selected in step a) contains a text string representing a date, convert this string to date first. Then change the format to the desired date format.

2. How to change the date format permanently in Excel?

To change a date format permanently, one needs to make changes to the date formats of the “Control Panel.” That is because the short and long date formats of Excel reflect the date settings of the “Control Panel.”

The steps to change the date settings of the “Control Panel” are listed as follows:

We must open the “Control Panel” first from the “Start” menu.
b. In the “Clock, Language, and Region” category, click “Change date, time, or number format.” It is available under the “Region and Language” option.
c. The “Region and Language” or “Region” dialog box opens. Under “Format,” we must select the region.
d. Enter the required short and long date formats under “Date and Time Formats.” To enter customized short and long date formats, click “Additional Settings.” The “Customize Format” dialog box opens. Make the changes in the “Date” tab and click “OK.”
e. Check the preview under “Examples” at the bottom of the “Region and Language” box. If the preview is alright, click “OK.”

The default date settings have been changed. Now, we should enter a date in any format in Excel. Then select the short or the long date format from the “Number Format” (in the “Number” section) of the “Home” tab.
The dates will appear in the format set in the “Control Panel.” So, the user need not change the format of each date manually.

3. How to change a date to a text string in Excel?

Let us change the date 22/1/2019 in cell A1 to a text string in Excel. The text string should be in the format yyyy-mm-dd.

The steps to change a date to a text string are listed as follows:
a. First, we must enter the formula =TEXT(A1, “yyyy-mm-dd”) in cell B1.
b. Then, press the “Enter” key.

The date in cell A1 (22/1/2019) is converted to 2019-01-22 in cell B1. We must note that the date in cell A1 is right-aligned, being a number. In contrast, the text in cell B1 is left-aligned.

Note: The TEXT function helps convert numbers to text strings. It is used to display values in a specific format. The syntax is TEXT(value,format_text). “Value” is the number to be converted to text. “Format_text” is the format in which the number should be displayed.

Recommended Articles

This article has been a guide to the Date Format in Excel. We discuss changing and customizing date formats in Excel, practical examples, and a downloadable Excel template. You may also look at these useful functions in Excel: –

  • Concatenate Columns in Excel
  • Convert Date to Text in Excel
  • Insert Date in Excel
  • Concatenate Date in Excel

Excel Custom Date Formats

You are not limited to using Excel’s built-in date formats. You can create your desired custom date formats in more than one way. You can even display your dates in a different language, change the appearance and order in which your dates are shown, add display color, and much more. In this article, you can learn how to format dates using a built-in format and how to format dates with use of the TEXT() function.

Using the DATE function available in Microsoft Excel is pretty simple as the function itself is very intuitive and self-explanatory. This function requires several variables to work, such as year, month and day, which can be inserted directly or entered as references to other cells with these variables. The Date function has the following syntax: DATE( year, month, day ). I have used the DATE function in many of my Calendars Templates, Project Gantt Chart, etc.

The DATE function can be used as a part of other functions or custom formulas and can also use other functions within for entering required variables. For example, one of the commonly used together with DATE functions is TODAY(), which returns the current date and can be used inside the DATE function and make it more dynamic.

The question that I have often been asked is how to format dates in the cell to display dates in alphanumerical format? Another issue is how to format dates using the TEXT() function? Additionally, why the date that is shown is either partly correct or displaying error when the spreadsheet is used in the non-English version of Microsoft Excel?

Examples

To follow along and see the examples described on this page in action, download the Excel file below.
Download the Example File (custom-date-formats.xlsx)

Change the Date Appearance with Format Cells Option

There a few methods in which you can approach these problems. The first method applies to scenarios where the content of the cell has to be displayed in some specific way, or you want to enter custom formatting. You can easily format the cell to show the date the way you need by following these steps:

  1. Select the cell (or multiple cells) you want to format
  2. Right-click on a cell (or cells) and select “Format Cells…” or use Ctrl+1 shortcut
  3. In the Format Cells dialog box choose the Date from the categories on the left
  4. Using the Locale drop-down list, choose a country or region of the date format you want to use
  5. Choose the desired format type in the Type section, then click OK to apply the format

Change the Date Format in Excel

The steps to apply custom formatting to the date entered into a cell or multiple cells are very similar.

  1. Select the cell (or multiple cells) you want to format
  2. Right-click on a cell (or cells) and select “Format Cells…” or use Ctrl+1 shortcut
  3. In the Format Cells window choose Custom from the categories on the left
  4. Select the desired formatting from the list in the Type section or enter your custom format type

Create a Custom Date Format in Excel

I won’t go through all custom formatting types that can be entered here as there are quite a few of them and it is quite frankly outside the scope of this article, but I will briefly touch upon the few of them. If you want to learn about all possible formatting types that you can create in Excel, please let me know in the comments below.

Here are some Date Format examples:

Format Code Cell Value Cell Appearance
dd/mm/yyyy 16/11/2018 16/11/2018
mm/dd/yyyy 16/11/2018 11/16/2018
mm-dd-yy 16/11/2018 11-16-18
mmmm d, yyyy 16/11/2018 November 16, 2018
d mmmm yyyy 16/11/2018 16 November 2018
d mmmm yyyy (dddd) 16/11/2018 16 November 2018 (Friday)
mm•dd•yyyy 16/11/2018 11•16•2018
“Date:” d mmmm yyyy 16/11/2018 Date: 16 November 2018

You can enter your custom format type by clicking in the area as shown on the image above. For example, if you want to display the date as November 16, 2018, you would enter the following: mmmm dd, yyyy. Check the table below for more date format options.

Format Code Description
dddd Full day of week names displayed as Monday-Sunday
ddd Abbreviated day of week names displayed as Mon-Sun
dd Days displayed with leading 0 as 01-31
d Days displayed as 1-31
mmmmm First letter of the month J-D
mmmm Month Names displayed in full as January-December
mmm Abbreviated month name displayed as Jan-Dec
mm Month number displayed with leading 0 as 01-12
m Month number displayed as 1-12
yyyy Year displayed in four digit format: 2018, 2019, etc.
y or yy Year displayed in two digit format: 18, 19, etc.

In this table, you can view some examples that you can apply to change the appearance of the date in the cell.

Format Code Date Appearance
d mmm ddd 6 Sep Thu
d mmm dddd 6 Sep Thursday
d mmm yyyy (dddd) 6 Sep 2018 (Thursday)
d mmm 6 Sep
d mmmm 6 September
dd/mm/yyyy 06/09/2018
dd-mm-yyyy 06-09-2018
d/m/yy 6/9/18
m/d/y 9/6/18
d mmm yy 6 Sep 18
mmm d, yy Sep 6, 18
d mmmm yyyy 6 September 2018
mmmm d, yyyy September 6, 2018
[$-C0A]mmmm d, yyyy febrero 6, 2018 (Spanish)

Additionally, the date can also appear in a different language by applying the language code to your formatting. For example, if you use the following language code [$-413] for Dutch, your date will appear in the Dutch language despite the system language settings of your computer. Language format can come in very handy, especially for use in spreadsheets where you want to display dates in various languages. I have posted the table with all applicable language codes at the bottom of this article.

All custom formatting applied via Excel built-in cell format option can be overwritten by conditional formatting or by accidental changes.

Format Dates with TEXT Function in Excel

If you are using the TEXT() function in your spreadsheet as a part of a formula or on its own, for applying a custom format to the date output, you can set the desired format right within the TEXT() function. To instruct the TEXT() function, you can use the same code that I have provided in the table above.

 =TEXT(A1,"mmmm d, yyyy") 

The formula above assumes that the date is in A1 (9/10/2018). The TEXT() function will apply the specified format to its output regardless of the initial format of the A1. So you should end up with the following output: September 9, 2018.

The output of the TEXT() function with a specified format cannot be changed with conditional formatting, which could sometimes be very useful. For example, you may not want to allow any system changes to override the format of your spreadsheet, such as system language changes. TEXT() function provides the ability to lock your set formats and can, to some extent prevent changes in the output.

One of many pros of using TEXT() function for setting a format of the date is the ability to set the different language for the output. You do this by including the language code with brackets to the format string, as shown in the example below

 =TEXT(A1,"[$-C0A]mmmm d, yyyy") 

Besides, you can make the TEXT() function even more dynamic by taking format string out of the worksheet function and placing it into any cell, then reference that cell in the format portion of the TEXT() function. Now you can change the format of the date by modifying the format string in the cell, without altering the TEXT() function.

 =TEXT(A1,C2) 

The formula in the example above assumes that A1 contains date and C2 includes the desired format string. The output of the TEXT() function will change every time you modify the format string in C2.

Custom Date Formats for Chart Labels and Axes

Custom Date format in format axis pane

As with almost everything else in Excel, few different methods can be used to apply a custom format to the dates in the chart axes and labels. The first method is to add the custom date format from the Format Axis pane. You should notice that the Linked to source box is unchecked.

You can also follow the other methods to add a custom format to the date. For example, you can modify the format of the data source first then apply this format to your chart axis by checking the Link to source box in Format Axis pane.

Any formats applied with TEXT() function to the data source whether in cells or chart axes, cannot be overridden.

Custom Location Codes for Dates

The table below includes all custom location codes for dates. You can use these location codes at the beginning of the format code string in square brackets for displaying month names and weekday names in other languages. The location/language code contains either three or four digits and/or letters, but if the leading digit is a zero, you do not need to include it.

Format Code Language/Location
0436 Afrikaans
041C Albanian
045E Amharic
0401 Arabic
042B Armenian
044D Assamese
082C Azeri (Cyrillic)
042C Azeri (Latin)
042D Basque
0423 Belarusian
0445 Bengali
0402 Bulgarian
0403 Catalan
045C Cherokee
0804 Chinese (Simplified)
0404 Chinese (Traditional)
041A Croatian
0405 Czech
0406 Danish
0465 Dhivehi
0413 Dutch
0466 Edo
0C09 English (Australian)
1009 English (Canadian)
0809 English (U.K.)
0409 English (U.S.)
0425 Estonian
0438 Faeroese
0464 Filipino
040B Finnish
040C French
0C0C French (Canadian)
0462 Frisian
0467 Fulfulde
0456 Galician
0437 Georgian
0407 German
0C07 German (Austrian)
0807 German (Swiss)
0408 Greek
0447 Gujarati
0468 Hausa
0475 Hawaiian
040D Hebrew
0439 Hindi
040E Hungarian
0469 Ibibio
040F Icelandic
0470 Igbo
0421 Indonesian
045D Inuktitut
0410 Italian
0411 Japanese
044B Kannada
0471 Kanuri
0460 Kashmiri (Arabic)
043F Kazakh
0457 Konkani
0412 Korean
0440 Kyrgyz
0476 Latin
0426 Latvian
0427 Lithuanian
042F Macedonian FYROM
043E Malay
044C Malayalam
043A Maltese
0458 Manipuri
044E Marathi
0450 Mongolian
0461 Nepali
0414 Norwegian Bokmal
0814 Norwegian Nynorsk
0448 Oriya
0472 Oromo
0463 Pashto
0429 Persian
0415 Polish
0416 Portuguese (Brazil)
0816 Portuguese (Portugal)
0446 Punjabi
0418 Romanian
0419 Russian
044F Sanskrit
0C1A Serbian (Cyrillic)
081A Serbian (Latin)
0459 Sindhi
045B Sinhalese
041B Slovak
0424 Slovenian
0477 Somali
0C0A Spanish
0441 Swahili
041D Swedish
045A Syriac
0428 Tajik
045F Tamazight (Arabic)
085F Tamazight (Latin)
0449 Tamil
0444 Tatar
044A Telugu
041E Thai
0873 Tigrigna (Eritrea)
0473 Tigrigna (Ethiopia)
041F Turkish
0442 Turkmen
0422 Ukrainian
0420 Urdu
0843 Uzbek (Cyrillic)
0443 Uzbek (Latin)
042A Vietnamese
0478 Yi
043D Yiddish
046A Yoruba

Other Notes about Custom Date Formats

You can quickly delete any custom formats created with built-in Format Cells option. To do so, open the Format Cells dialog box, select Custom from the categories on the left, select the custom format from the list then click Delete then click OK. All values that use the custom format which you want to delete will revert to the General format.

All custom date formats that you create belong to the workbook in which they were created. You will have to recreate the custom formats again in the new workbook or copy/paste the formatting from the file where you have initially created them. You can achieve this by copying and pasting the formatted cell, by copying the format code and pasting this code into the Format Cells dialog box or by using the Format Painter tool.

References

  • Excel Custom Number Format by Mynda Treacy, Excel MVP (MyOnlineTrainingHub.com)
  • Excel TEXT Function by Dave and Lisa Bruns (ExcelJet.net)

Excel позволяет создать свой (пользовательский) формат ячейки. Многие знают об этом, но очень редко пользуются из-за кажущейся сложности. Однако это достаточно просто, главное понять основной принцип задания формата.

Для того, чтобы создать пользовательский формат необходимо открыть диалоговое окно Формат ячеек и перейти на вкладку Число. Можно также воспользоваться сочетанием клавиш Ctrl + 1.

В поле Тип вводится пользовательские форматы, варианты написания которых мы рассмотрим далее.

Посмотрите простые примеры использования форматирования. В столбце А – значение без форматирования, в столбце B – с использованием пользовательского формата (применяемый формат в столбце С)

Синий, зеленый, красный, фиолетовый, желтый, белый, черный и голубой.

Стоит обратить внимание, что форматы даты можно комбинировать между собой. Например, формат “ДД.ММ.ГГГГ” отформатирует дату в привычный нам вид 31.12.2017, а формат “ДД МММ” преобразует дату в вид 31 Дек.

Если иметь ввиду российские региональные настройки, то Excel позволяет вводить дату очень разными способами – и понимает их все:

Внешний вид (отображение) даты в ячейке может быть очень разным (с годом или без, месяц числом или словом и т.д.) и задается через контекстное меню – правой кнопкой мыши по ячейке и далее Формат ячеек (Format Cells):

Время вводится в ячейки с использованием двоеточия. Например

По желанию можно дополнительно уточнить количество секунд – вводя их также через двоеточие:

И, наконец, никто не запрещает указывать дату и время сразу вместе через пробел, то есть

Для ввода сегодняшней даты в текущую ячейку можно воспользоваться сочетанием клавиш Ctrl + Ж (или CTRL+SHIFT+4 если у вас другой системный язык по умолчанию).

Если скопировать ячейку с датой (протянуть за правый нижний угол ячейки), удерживая правуюкнопку мыши, то можно выбрать – как именно копировать выделенную дату:

Если Вам часто приходится вводить различные даты в ячейки листа, то гораздо удобнее это делать с помощью всплывающего календаря:

Если нужно, чтобы в ячейке всегда была актуальная сегодняшняя дата – лучше воспользоваться функцией СЕГОДНЯ (TODAY):

Как Excel на самом деле хранит и обрабатывает даты и время

Если выделить ячейку с датой и установить для нее Общий формат (правой кнопкой по ячейке Формат ячеек – вкладка ЧислоОбщий), то можно увидеть интересную картинку:

То есть, с точки зрения Excel, 27.10.2012 15:42 = 41209,65417

На самом деле любую дату Excel хранит и обрабатывает именно так – как число с целой и дробной частью. Целая часть числа (41209) – это количество дней, прошедших с 1 января 1900 года (взято за точку отсчета) до текущей даты. А дробная часть (0,65417), соответственно, доля от суток (1сутки = 1,0)

Из всех этих фактов следуют два чисто практических вывода:

  • Во-первых, Excel не умеет работать (без дополнительных настроек) с датами ранее 1 января 1900 года. Но это мы переживем! ;)
  • Во-вторых, с датами и временем в Excel возможно выполнять любые математические операции. Именно потому, что на самом деле они – числа! А вот это уже раскрывает перед пользователем массу возможностей.

Количество дней между двумя датами

Считается простым вычитанием – из конечной даты вычитаем начальную и переводим результат в Общий (General) числовой формат, чтобы показать разницу в днях:

Количество рабочих дней между двумя датами

Здесь ситуация чуть сложнее. Необходимо не учитывать субботы с воскресеньями и праздники. Для такого расчета лучше воспользоваться функцией ЧИСТРАБДНИ(NETWORKDAYS) из категории Дата и время. В качестве аргументов этой функции необходимо указать начальную и конечную даты и ячейки с датами выходных (государственных праздников, больничных дней, отпусков, отгулов и т.д.):

Примечание: Эта функция появилась в стандартном наборе функций Excel начиная с 2007 версии. В более древних версиях сначала необходимо подключить надстройку Пакета анализа. Для этого идем в меню Сервис – Надстройки (Tools – Add-Ins) и ставим галочку напротив Пакет анализа (Analisys Toolpak). После этого в Мастере функций в категории Дата и время появится необходимая нам функция ЧИСТРАБДНИ (NETWORKDAYS).

Функция ГОД в Excel

Возвращает год как целое число (от 1900 до 9999), который соответствует заданной дате. В структуре функции только один аргумент – дата в числовом формате. Аргумент должен быть введен посредством функции ДАТА или представлять результат вычисления других формул.

Пример использования функции ГОД:

Функция МЕСЯЦ в Excel: пример

Возвращает месяц как целое число (от 1 до 12) для заданной в числовом формате даты. Аргумент – дата месяца, который необходимо отобразить, в числовом формате. Даты в текстовом формате функция обрабатывает неправильно.

Примеры использования функции МЕСЯЦ:

ДЕНЬНЕД

Задача оператора ДЕНЬНЕД – выводить в указанную ячейку значение дня недели для заданной даты. Но формула выводит не текстовое название дня, а его порядковый номер. Причем точка отсчета первого дня недели задается в поле «Тип». Так, если задать в этом поле значение «1», то первым днем недели будет считаться воскресенье, если «2» — понедельник и т.д. Но это не обязательный аргумент, в случае, если поле не заполнено, то считается, что отсчет идет от воскресенья. Вторым аргументом является собственно дата в числовом формате, порядковый номер дня которой нужно установить. Синтаксис выглядит так:

=ДЕНЬНЕД(Дата_в_числовом_формате;[Тип])

“ВЫБОР”.

Теперь предположим, что вы хотите получить произвольное название месяца или имя на другом языке вместо числа или обычного имени.

В этой ситуации вам поможет функция ВЫБОР и уже пройденная нами функция МЕСЯЦ. Построим формулу. Для этого нам необходимо указать пользовательское имя для всех 12 месяцев в функции и использовать функцию месяца, чтобы получить номер месяца из даты.

=ВЫБОР(МЕСЯЦ(A1);”Январь”;”Фев”;”Март”;”Апр”;”Май”;”Июнь”;”Июль”;”Авг”;”Сен”;”Октябрь”;” Ноябрь”;”декабрь”)

Таким образом, когда функция месяца возвращает номер месяца от даты, функция выбора будет возвращать произвольное имя месяца вместо этого числа.

НОМНЕДЕЛИ

Предназначением оператора НОМНЕДЕЛИ является указание в заданной ячейке номера недели по вводной дате. Аргументами является собственно дата и тип возвращаемого значения. Если с первым аргументом все понятно, то второй требует дополнительного пояснения. Дело в том, что во многих странах Европы по стандартам ISO 8601 первой неделей года считается та неделя, на которую приходится первый четверг. Если вы хотите применить данную систему отсчета, то в поле типа нужно поставить цифру «2». Если же вам более по душе привычная система отсчета, где первой неделей года считается та, на которую приходится 1 января, то нужно поставить цифру «1» либо оставить поле незаполненным. Синтаксис у функции такой:

=НОМНЕДЕЛИ(дата;[тип])

Формула условия для дат с функцией ДАТАЗНАЧ (DATEVALUE)

Иногда случается, что записать дату непосредственно в функцию ЕСЛИ, не ссылаясь ни на какую ячейку. В этом случае возникают некоторые сложности.

В отличие от многих других функций Excel, ЕСЛИ не может распознавать даты и интерпретирует их как текст, как простые текстовые строки.

Поэтому вы не можете выразить свое логическое условие просто как >«15.07.2019» или же >15.07.2019. Увы, ни один из приведенных вариантов не верен.

Чтобы функция ЕСЛИ распознала дату в вашем логическом условии именно как дату, вы должны обернуть ее в функцию ДАТАЗНАЧ (в английском варианте – DATEVALUE).

Например, ДАТАЗНАЧ(«15.07.2019»).

Полная формула ЕСЛИ может иметь следующую форму:

=ЕСЛИ(B2<ДАТАЗНАЧ(“10.09.2019″),”Поступил”,”Ожидается”)

Как показано на скриншоте, эта формула ЕСЛИ оценивает даты в столбце В и возвращает «Послупил», если дата поступления до 10 сентября. В противном случае формула возвращает «Ожидается».

Расширенные формулы ЕСЛИ для будущих и прошлых дат

Предположим, вы хотите отметить только те даты, которые отстоят от текущей более чем на 30 дней.

Выделим даты, отстоящие более чем на месяц от текущей, в прошлом. Укажем для них «Более месяца назад». Запишем это условие:

=ЕСЛИ(СЕГОДНЯ()-B2>30,”Более месяца назад”,””)

Если условие не выполнено, то в ячейку запишем пустую строку “”.

А для будущих дат, также отстоящих более чем на месяц, укажем «Ожидается».

=ЕСЛИ(B2-СЕГОДНЯ()>30,”Ожидается”,””)

Если все результаты попробовать объединить в одном столбце, то придется составить выражение с несколькими вложенными функциями ЕСЛИ:

=ЕСЛИ(СЕГОДНЯ()-B2>30,”Более месяца назад”, ЕСЛИ(B2-СЕГОДНЯ()>30,”Ожидается”,””))

Перевод разных написаний дат

Разные системы в выгрузках выдают даты по-разному, например: 12.07.2016 12-07-16 16-07-12 и так далее. Иногда месяца пишут текстом. Для того, чтобы привести даты к одному формату мы используем функцию ДАТА:

Синтаксис: =ДАТА(ЛЕВСИМВ(A2;4);ПСТР(A2;5;2);ПРАВСИМВ(A2;2))

Данный вариант подходит, когда количество символов в дате одинаковое. Если вы работаете с однотипными выгрузками еженедельно, создание дополнительного столбца и протягивание формулы будет простым решением.

Получение значения даты

С помощью формулы ЗНАЧ мы выводим текстовое значение даты, потом его форматируем как Дату:

Синтаксис: =ЗНАЧЕН(A7)

Умножение текстового значения на единицу

Принцип аналогичный предыдущему, только мы текстовое значение умножаем на единицу и после этого форматируем как дату:

Примечание: если дата определилась как текст, то вы не сможете делать группировки. При этом дата будет выровнена по левому краю. Excel выравнивает числа и даты по правому краю.

Синтаксис

=DATE(year, month, day) – английская версия

=ДАТА(год; месяц; день) – русская версия

Аргументы

  • Year (Год) – значение года, которое важно отобразить в дате;
  • Month (Месяц) – значение месяца, которое важно отобразить в дате;
  • Day (День) – значение дня, которое важно отобразить в дате.

Вставка текущей даты и времени.

В Microsoft Excel вы можете сделать это в виде статического или динамического значения.

Как вставить сегодняшнюю дату как статическую отметку.

Для начала давайте определим, что такое отметка времени. Отметка времени фиксирует «статическую точку», которая не изменится с течением времени или при пересчете электронной таблицы. Она навсегда зафиксирует тот момент, когда ее записали.

Таким образом, если ваша цель – поставить текущую дату и/или время в качестве статического значения, которое никогда не будет автоматически обновляться, вы можете использовать одно из следующих сочетаний клавиш:

  • Ctrl + ; (в английской раскладке) или Ctrl+Shift+4 (в русской раскладке) вставляет сегодняшнюю дату в ячейку.
  • Ctrl + Shift + ; (в английской раскладке) или Ctrl+Shift+6 (в русской раскладке) записывает текущее время.
  • Чтобы вставить текущую дату и время, нажмите Ctrl + ; затем нажмите клавишу пробела, а затем Ctrl + Shift +;

Скажу прямо, не все бывает гладко с этими быстрыми клавишами. Но по моим наблюдениям, если при загрузке файла у вас на клавиатуре был включен английский, то срабатывают комбинации клавиш на английском – какой бы язык бы потом не переключили для работы. То же самое – с русским.

Как сделать, чтобы дата оставалась актуальной?

Если вы хотите вставить текущую дату, которая всегда будет оставаться актуальной, используйте одну из следующих функций:

  • =СЕГОДНЯ()- вставляет сегодняшнюю дату.
  • =ТДАТА()- использует текущие дату и время.

В отличие от нажатия специальных клавиш, функции ТДАТА и СЕГОДНЯ всегда возвращают актуальные данные.

А если нужно вставить текущее время?

Здесь рекомендации зависят от того, что вы далее собираетесь с этим делать. Если нужно просто показать время в таблице, то достаточно функции ТДАТА() и затем установить для этой ячейки формат «Время».

Если же далее на основе этого вы планируете производить какие-то вычисления, то тогда, возможно, вам будет лучше использовать формулу

=ТДАТА()-СЕГОДНЯ()

В результате количество дней будет равно нулю, останется только время. Ну и формат времени все равно нужно применить.

При использовании формул имейте в виду, что:

  • Возвращаемые значения не обновляются непрерывно, они изменяются только при повторном открытии или пересчете электронной таблицы или при запуске макроса, содержащего функцию.
  • Функции берут всю информацию из системных часов вашего компьютера.

Как поставить неизменную отметку времени автоматически формулами?

Допустим, у вас есть список товаров в столбце A, и, как только один из них будет отправлен заказчику, вы вводите «Да» в колонке «Доставка», то есть в столбце B. Как только «Да» появится там, вы хотите автоматически зафиксировать в колонке С время, когда это произошло. И менять его уже не нужно.

Для этого мы попробуем использовать вложенную функцию ИЛИ с циклическими ссылками во второй ее части:

=ЕСЛИ(B2=”Да”; ЕСЛИ(C2=””;ТДАТА(); C2); “”)

Где B – это колонка подтверждения доставки, а C2 – это ячейка, в которую вы вводите формулу и где в конечном итоге появится статичная отметка времени.

В приведенной выше формуле первая функция ЕСЛИ проверяет B2 на наличие слова «Да» (или любого другого текста, который вы решите ввести). И если указанный текст присутствует, она запускает вторую функцию ЕСЛИ. В противном случае возвращает пустое значение. Вторая ЕСЛИ – это циклическая формула, которая заставляет функцию ТДАТА() возвращать сегодняшний день и время, только если в C2 еще ничего не записано. А если там уже что-то есть, то ничего не изменится, сохранив таким образом все существующие метки.

О работе с функцией ЕСЛИ читайте более подробно здесь.

Если вместо проверки какого-либо конкретного слова вы хотите, чтобы временная метка появлялась, когда вы хоть что-нибудь пишете в указанную ячейку (это может быть любое число, текст или дата), то немного изменим первую функцию ЕСЛИ для проверки непустой ячейки:

=ЕСЛИ(B2<>””; ЕСЛИ(C2=””;ТДАТА(); C2); “”)

Примечание. Чтобы эта формула работала, вы должны разрешить циклические вычисления на своем рабочем листе (вкладка Файл – параметры – Формулы – Включить интерактивные вычисления). Также имейте в виду, что в основном не рекомендуется делать так, чтобы ячейка ссылалась сама на себя, то есть создавать циклические ссылки. И если вы решите использовать это решение в своих таблицах, то это на ваш страх и риск.

Складывать и вычитать календарные дни

Excel позволяет добавлять к дате и вычитать из нее нужное количество дней. Никаких специальных формул для этого не нужно. Достаточно сложить ячейку, в которую ввели дату, и необходимое число суток.

Например, вам необходимо создать резерв по сомнительным долгам в налоговом учете. В том числе нужно просчитать, когда у покупателя возникнет задолженность со сроком 45 дней после дня реализации. Для этого в одну ячейку внесите дату отгрузки. К примеру, это ячейка D2. Тогда формула будет выглядеть так: =D2+45. Вычитаются дни по аналогичному принципу. Главное, чтобы ячейка с датой, к которой будете прибавлять число, имела правильный формат. Чтобы это проверить, нажмите правой кнопкой мыши на ячейку, выберите «Формат ячеек» и удостоверьтесь, что установлен формат «Дата».

Как выглядит формат ячейки в Excel

Таким же образом можно посчитать и количество дней между двумя датами. Просто вычтите из более поздней даты более раннюю. Результат Excel покажет в виде числа, поэтому ячейку с итогом переведите в общий формат: вместо «Дата» выберите «Общий».

К примеру, необходимо посчитать, сколько календарных дней пройдет с 05.11.2019 по 31.12.2019. Для этого введите эти даты в разные ячейки, а в отдельной ячейке поставьте знак «=». Затем вычтите из декабрьской даты ноябрьскую. Получится 56 дней. Помните, что в этом случае в подсчет войдет последний день, но не войдет первый. Если вам необходимо, чтобы итог включал оба дня, прибавьте к формуле единицу. Если же, наоборот, нужно посчитать количество дней без учета обеих дат, то единицу необходимо вычесть.

Добавить к дате рабочие дни

Функция РАБДЕНЬ позволяет точно посчитать дату через нужное количество рабочих дней. Эта функция состоит из трех элементов:

  • начальная дата – ставят ссылку на ячейку с датой, к которой функция будет прибавлять рабочие дни;
  • число рабочих дней – ставят количество рабочих дней, которое необходимо прибавить к начальной дате;
  • праздники (необязательный) – ставят ссылку на диапазон с датами праздников.

Например, директор дал вам поручение, которое необходимо выполнить за 25 рабочих дней. Допустим, сегодня вторник, 5 ноября 2019 года. Эту дату вносим в ячейку A1. Функция =РАБДЕНЬ(A1;25) определит крайний день, когда вы должны его выполнить, — 10 декабря 2019 года. При этом не забудьте поставить в ячейке с результатом формат «Дата».

Помните, что функция РАБДЕНЬ автоматически убирает из подсчетов только субботы и воскресенья. О праздниках Excel не знает. Их нужно заносить в функцию вручную. Чтобы вы не запутались, мы подготовили файл, в который уже внесли все праздники 2020 года. Ищите его в электронной версии статьи.

Как прибавить (вычесть) несколько недель к дате

Когда требуется прибавить (вычесть) несколько недель к определенной дате, Вы можете воспользоваться теми же формулами, что и раньше. Просто нужно умножить количество недель на 7:

  • Прибавляем N недель к дате в Excel:

    = A2 + N недель * 7

    Например, чтобы прибавить 3 недели к дате в ячейке А2, используйте следующую формулу:

    =A2+3*7

  • Вычитаем N недель из даты в Excel:

    = А2 - N недель * 7

    Чтобы вычесть 2 недели из сегодняшней даты, используйте эту формулу:

    =СЕГОДНЯ()-2*7
    =TODAY()-2*7

Добавление лет к датам в Excel осуществляется так же, как добавление месяцев. Вам необходимо снова использовать функцию ДАТА (DATE), но на этот раз нужно указать количество лет, которые Вы хотите добавить:

= ДАТА(ГОД(дата) + N летдатадата))
= DATE(YEAR(дата) + N лет, MONTH(дата), DAY(дата))

На листе Excel, формулы могут выглядеть следующим образом:

  • Прибавляем 5 лет к дате, указанной в ячейке A2:

    =ДАТА(ГОД(A2)+5;МЕСЯЦ(A2);ДЕНЬ(A2))
    =DATE(YEAR(A2)+5,MONTH(A2),DAY(A2))

  • Вычитаем 5 лет из даты, указанной в ячейке A2:

    =ДАТА(ГОД(A2)-5;МЕСЯЦ(A2);ДЕНЬ(A2))
    =DATE(YEAR(A2)-5,MONTH(A2),DAY(A2))

Чтобы получить универсальную формулу, Вы можете ввести количество лет в ячейку, а затем в формуле обратиться к этой ячейке. Положительное число позволит прибавить годы к дате, а отрицательное – вычесть.

Как отличить обычные даты Excel от «текстовых дат»

Импортированные данные (или данные, введенные неправильно) могут выглядеть как обычные даты Excel, но они не ведут себя так, как выглядят. Microsoft Excel обрабатывает такие записи как текст. Поэтому вы не сможете правильно отсортировать таблицу в хронологическом порядке, а также использовать эти «неправильные даты» в формулах, сводных таблицах, диаграммах или любом другом инструменте Excel, который работает с временем.

Сначала давайте изучим несколько признаков, которые могут помочь определить, записана в ячейке датировка либо текст.

Даты

Текстовые значения

· Выровнено по правому краю.

· Указан формат даты в поле «Числовой формат» на вкладке «Главная » — «Число» .

· По левому краю по умолчанию.

· Общий формат отображается в поле «Число» на вкладке «Главная» — «Число».

·В строке формул может быть виден апостроф перед содержимым ячейки.

Их можно легко распознать, немного расширив столбцы, выделив один из них, вы­брав команду Формат ► Ячейки ► Выравнивание (Format ► Cells ► Alignment) и для па­раметра По горизонтали (Horizontal) выбрав значение Общий (General) (это вид ячеек по умолчанию). Щелкните кнопку ОК и внимательно просмотрите на таблицу. Если какие-либо значения не выровнены по правому краю, значит Excel не считает их датами.

Как конвертировать текст в дату в Excel

Когда возникает подобная проблема, скорее всего, вы захотите перевести эти текстовые значения в обычные даты Excel, чтобы вы могли ссылаться на них в формулах для выполнения различных вычислений. И, как это часто бывает в Экселе, есть несколько способов решения этой задачи.

Математические операции для преобразования текста в дату

Помимо использования функций Excel, о которых мы говорили чуть выше, вы можете выполнить простую математическую операцию, чтобы заставить программу выполнить реорганизацию строки в дату. Обязательное условие: операция не должна изменять ее значение (порядковый номер дня). Звучит немного сложно? Следующие примеры помогут разобраться!

Предполагая, что ваши данные находятся в ячейке A1, вы можете использовать любую из следующих формул, а затем применить формат даты к ячейке:

  • Сложение: =A1 + 0
  • Умножение: =A1 * 1
  • Деление: =A1 / 1
  • Двойное отрицание: =–A1

Как вы можете убедиться, математические операции могут помочь с датами (строки 3,4.,5,7), временем (строки 2 и 6), а также числами, отформатированными как текст (строка 8).

Иногда результат даже отображается в виде даты автоматически, и вам не нужно беспокоиться об изменении формата ячейки.

Как превратить текстовые строки с пользовательскими разделителями в даты

Если запись содержит какой-либо разделитель, отличный от косой черты (/) или тире (-), функции Excel не смогут распознать их как даты и вернут ошибку #ЗНАЧ!. Чаще всего такие «неправильные» разделители – это пробел и запятая.

Чтобы это исправить, вы можете запустить инструмент поиска и замены, чтобы заменить этот неподходящий разделитель, к примеру, косой чертой (/):

  • Выберите все ячейки, которые вы хотите превратить в даты.
  • Нажмите Ctrl + H, чтобы открыть диалоговое окно «Найти и заменить».
  • Введите свой пользовательский разделитель (запятую, к примеру) в поле Найти и косую черту в Заменить.
  • Нажмите Заменить все.

Теперь у ДАТАЗНАЧ или ЗНАЧЕН должно быть проблем с конвертацией текстовых строк в даты. Таким же образом вы можете исправить записи, содержащие любой другой разделитель, например, пробел или обратную косую черту.

Если вы предпочитаете решение на основе формул, вы можете использовать функцию ПОДСТАВИТЬ (SUBSTITUTE в английской версии), как это мы делали на одном из скриншотов ранее:

=ДАТАЗНАЧ(ПОДСТАВИТЬ(A12;”,”;”.”))

И текстовые строки преобразуются в даты, все при помощи одной формулы.

Как видите, функции ДАТАЗНАЧ или ЗНАЧЕН довольно мощные, но они, к сожалению, имеют свои ограничения. Например, если вы пытаетесь работать со сложными конструкциями, такими как четверг, 01 января 2015 г., ни одна из них не сможет помочь.

К счастью, есть решение без формул, которое может справиться с этой задачей, и следующий раздел даст нам пошаговое руководство.

Исправление записей с двузначными годами.

Современные версии Microsoft Excel достаточно умны, чтобы обнаружить некоторые очевидные ошибки в ваших данных, или, точнее, сказать, что Эксель считает ошибкой. Когда это произойдет, вы увидите индикатор ошибки (маленький зеленый треугольник) в верхнем левом углу клетки, и, когда вы выделите её, появится восклицательный знак.
При нажатии на восклицательный знак отобразятся несколько параметров, относящихся к вашим данным. В случае двухзначного года программа спросит, хотите ли вы преобразовать его в 19XX или 20XX.

Если у вас имеется несколько записей этого типа, вы можете исправить их все одним махом – выделите все ячейки с ошибками, затем нажмите на восклицательный знак и выберите соответствующую опцию.

Источники

  • https://micro-solution.ru/excel/formatting/custom-format
  • https://www.planetaexcel.ru/techniques/6/88/
  • https://exceltable.com/funkcii-excel/funkcii-raboty-datami
  • https://lumpics.ru/functions-date-and-time-in-excel/
  • https://zen.yandex.ru/media/id/5a25282b7800192677cc044f/5dea1b66e4fff000adb66297
  • https://mister-office.ru/funktsii-excel/if-with-dates.html
  • https://needfordata.ru/blog/rabota-s-datami-v-excel-ustranenie-tipovyh-oshibok
  • https://excelhack.ru/data-funkciya-v-excel/
  • https://mister-office.ru/formuly-excel/insert-dates-excel.html
  • https://zen.yandex.ru/media/id/593a7db8d7d0a6439bc26099/5e254f062b61697618a72b0c
  • https://office-guru.ru/excel/kak-skladyvat-i-vychitat-daty-dni-nedeli-mesjacy-i-gody-v-excel-438.html
  • https://mister-office.ru/excel/convert-text-date.html

Dates play an important role when we need to analyze trends. This is one of the most important things which you need to capture in the right way. Apart from the basic date format which is used by Excel to store dates. There are some other data formats that are acceptable.

Now the thing is: When we capture a date in the wrong format Excel treats that date as a text and, then we can’t use that date further in any calculation.

When it comes to textual data formats there is no one particular thing. It depends on the person who is entering those dates. The bottom line is: We do need some methods which we can use to convert a text to an actual date with the right format.

So today, in this post, I’d like to share with you 10 methods that we can use to convert a text to date format in Excel. For converting a text to date we need to use a combination of different functions.

So let’s get started.

Using the DATEVALUE function is a basic method to convert a date into an actual date which is stored as text.

Let’s say you have a list of dates in your worksheet and all the cells where dates are entered have text format but all those dates are in the correct date format.

In the below example, we have a date in a cell but when I try to add a number to that date I’m getting an error, even though the format of the data is correct.

Excel datevalue function to convert text to date

But if you look at the cell format, it’s text. So here, is the best way to use the DATEVALUE function. You just need to refer to that cell in the function and it will convert that data into actual date.

convert text to date list with datevalue function

And, then you can change its format to date.

Important Note: There are some situations where DATEVALUE can’t help us to get a date from a text. There is n number of irregular formats of dates and to deal with all those we need to create a custom formula using different functions.

In the next 10 examples, I will share with you how can we use these different functions.

text to date list

2. Date with Back Slashes

The Excel date system supports dates with forwarding slashes. And, if we have a date where we have backslashes, it will treat it as a text.

convert text to date with black slashes invalid

To solve this problem we can use the below formula.

=DATE(RIGHT(A2,4),MID(A2,4,2),LEFT(A2,2))
convert text to date with black slashes

3. Date with Month Name

Now, we have a date format where the month is entered with its name. For Excel, this is not a date anymore, even if it’s presenting a date clearly.

convert text to date with month name full

The below formula can help us with this.

=DATEVALUE(RIGHT(A3,2)&"-"&TEXT(MID(A3,6,3),"MMM")&"-"&LEFT(A3,4))
convert text to date with month name full formula

4. Date with Dots

It’s a common kind you problem where we get dots inside a date. This is a kind of format used by people who are not aware that this is not a proper date format.

And, this is the formula to correct it.

=DATE(RIGHT(A4,4),MID(A4,4,2),LEFT(A4,2))

5. Date with the Month Name and a Comma

This format is almost the same as the format we discussed in point 3.

And, we can correct it with the below formula.

=DATEVALUE(LEFT(A5,2)&"-"&TEXT(MID(A5,4,3),"MMM")&"-"&RIGHT(A5,4))

6. Date with the Day Name

Sometimes people store a date with the day’s name. And, if that date is not in a proper format Excel will treat it as text.

Use this formula for this type of text date.

=DATEVALUE(MID(A6,FIND(",",A6)+6,2)&"-"&MID(A6,FIND(",",A6)+2,3)&"-"&RIGHT(A6,4))

7. Date with a Day Name in the End

Here we have a date with the day name at the end. Now, the problem with this format is it has a comma between the date and day name.

But, we can get the valid date using the below formula.

=DATEVALUE(MID(A7,10,2)&"-"&MID(A7,6,3)&"-"&LEFT(A7,4))

8. Date Having a Suffix with Day

We have a “th” suffix with the day number and it makes it a text instead of a date as Excel is not able to recognize it.

The below formula will help you to get the real date.

=DATEVALUE(LEFT(A8,FIND("th",A8)-1)&"-"&MID(A8,FIND(" ",A8)+1,3)&"-"&RIGHT(A8,4))

9. Date with Space Between Day, Month, and Year

When we have a date format with space between day, month, and year, we can use the below formula to correct the date format.

=DATE(RIGHT(A9,4),MID(A9,4,2),LEFT(A9,2))

10. Date with Short Month Name

With a date format where we have a short month name at the start of the date.

We can use the following formula to convert it to a valid date format.

=DATEVALUE(MID(A10,5,2)&"-"&LEFT(A10,3)&"-"&RIGHT(A10,4))

11. Date Without Any Space Between Day, Month, and Year

And for a date where there is no space between day, month, and year.

The below formula will help us to get the correct date format.

=DATE(RIGHT(A11,2),MID(A11,3,2),LEFT(A11,2))

In this guide, we’ll learn how to change date format in Excel. Date and Time data is an integral part of any statistical document or sheet. It is important to accurately track and analyze events, sales, figures, and others.

By convention, Excel uses a general data format that may be as per your need. But in most cases, that format may need to be customized.

Changing the format of Date in a particular cell or all the cells in your Excel sheet is an easy process and doesn’t require any complex methodologies. Excel provides a wide range of formatting options based on Location and Languages which helps in better date formatting in native language and style. Also, For some Languages there is also features to select from different Calendar types.

Follow the below step-by-step tutorial to change date format in Excel quickly and easily.

Step 1. Select the range of cells containing the date

To start with, select the cell values where want to change the date format, as shown in the image below.

Select Date in Excel
Sample selection of dates in default formatting option

Step 2. Go to Number Format dropdown

  • To select ‘Number Format’, go to ‘Home‘ in the option menu and look for Number Format, as shown below
  • Then from the drop-down menu, select ‘More Number Formats‘ to reveal the ‘Number Format’ dialogue menu.
Select Number Format in Excel
Select Number Format
  • Alternatively, you may directly go to Number Format, by right-clicking on the selected cell/s
  • Click on ‘Number Format’.
Right Click and select Number Format in Excel
Right Click and select Number Format

Step 3. Choose Date

  • From the Category menu on the right, choose ‘Date‘.
Format Date option menu in Excel
Format Date option menu

Now, to apply any date formatting type, select it from the right panel of the pop-up menu of Number Format. Click on ‘OK‘ to apply the formatting to the selected cell/s.

Note: You may check the date format implementation in the ‘Sample‘ at the top of the menu option

Choose the Date Type

The general option type to choose from a variety of Date Formatting options. Scroll down in this section to reveal a plethora of options for formatting, ranging from date, text (month name), year, and others.

This option can be perceived as the display menu, as the formatting options in this will keep on changing as per the selection in Locale(Location) and Calendar type.

General Date Formatting in Excel
General Date Formatting

Choose the Locale (location)

This option features the Location or Language options to help format the date accordingly. This option is probably the most used option as users require to format the date according to their or audience preference as per the native formatting style, based on language and location.

Choose any language or Location from this options menu. After selecting, all the supported date format options available for that particular locale will be available for selecting in the above Type menu.

selecting locale (language) in Excel
selecting locale (language) in date formatting

Choose the type of calendar

This option reveals different calendar types available based on the Locale(Location) selected from the above option menu. This formatting option is only available for certain Locale and not all.

As shown in our example below, the variety of calendar types available for selection are only available for the Locale (location) selected (here, Arabia), for other locales the calendar type might be different or not at all present.

Selecting Calendar type in Date Formatting in Excel
Selecting Calendar type in Date Formatting

To apply selected formatting, you will need to click ‘OK‘ after selection to apply to your dates.

Conclusion

That’s It! You can now easily convert your dates to your desired format style easily.

We hope you learned and enjoyed this lesson and we’ll be back soon with another awesome Excel tutorial at QuickExcel!

In this article, we will learn How to Combine Text and a Formatted Date in Excel.

Excel treats values to many formats like number, date, time, text, percentage or currency. These can be changed into each other. Excel converts numbers to text to use numbers as text in formulas like vlookup with numbers and text. The Excel TEXT function lets you convert the number to text. The TEXT function in Excel is used to convert numbers into text. The fun part is you can format that number to show it in the desired format. For example format a yy-mm-dd date into dd-mm-yy format. Add currency signs before a  number and many more.

TEXT function is a string function which converts any value to a given format. The result may seem that it is a number but it’s in text format.

All of these might be confusing to understand. Let’s understand how to use the function using an example. Here we have some examples to convert date values to text format or any other required format.

Convert the value in A2 cell.

“0”: returns the general text format.

As you can see we got numbers as text output because the significance number always varied.

Here we have some numbers to convert to text format or any other required format.

As you can see the value in the output cell is in Text format. 

Sometimes you are needed to add 0 before some fixed digit of numbers like phone number or pin number. Use this Text formula to do so…

If you have N digits of number then in text format argument write n+1 0s.

Write this text formula to add currency.

As you can see we got numbers as text output because the significance number always varied.

This code is divided into four individual functions. The main function is NUM_TO_IND_RUPEE_WORD. And other three functions GetHunderds(), GetTens() and GetDigits are helping function that help the main function to form the string.

Function NUM_TO_IND_RUPEE_WORD(ByVal MyNumber, Optional incRupees As Boolean = True)

 Dim Crores, Lakhs, Rupees, Paise, Temp

 Dim DecimalPlace As Long, Count As Long

 Dim myLakhs, myCrores

 ReDim Place(9) As String

 Place(2) = » Thousand «: Place(3) = » Million «

 Place(4) = » Billion «: Place(5) = » Trillion «

 ‘ String representation of amount.

 MyNumber = Trim(Str(MyNumber))

 ‘ Position of decimal place 0 if none.

 DecimalPlace = InStr(MyNumber, «.»)

 ‘ Convert Paise and set MyNumber to Rupees amount.

 If DecimalPlace > 0 Then

  Paise = GetTens(Left(Mid(MyNumber, DecimalPlace + 1) & «00», 2))

  MyNumber = Trim(Left(MyNumber, DecimalPlace — 1))

 End If

 myCrores = MyNumber 10000000

 myLakhs = (MyNumber — myCrores * 10000000) 100000

 MyNumber = MyNumber — myCrores * 10000000 — myLakhs * 100000

 Count = 1

 Do While myCrores <> «»

  Temp = GetHundreds(Right(myCrores, 3))

  If Temp <> «» Then Crores = Temp & Place(Count) & Crores

  If Len(myCrores) > 3 Then

    myCrores = Left(myCrores, Len(myCrores) — 3) 

  Else

    myCrores = «»

  End If

  Count = Count + 1

 Loop

 Count = 1

 Do While myLakhs <> «»

  Temp = GetHundreds(Right(myLakhs, 3))

  If Temp <> «» Then Lakhs = Temp & Place(Count) & Lakhs

  If Len(myLakhs) > 3 Then

   myLakhs = Left(myLakhs, Len(myLakhs) — 3)

  Else

   myLakhs = «»

  End If

  Count = Count + 1

 Loop

 Count = 1

 Do While MyNumber <> «»

  Temp = GetHundreds(Right(MyNumber, 3))

  If Temp <> «» Then Rupees = Temp & Place(Count) & Rupees

  If Len(MyNumber) > 3 Then

   MyNumber = Left(MyNumber, Len(MyNumber) — 3)

  Else

   MyNumber = «»

  End If

  Count = Count + 1

 Loop

 Select Case Crores

  Case «»: Crores = «»

  Case «One»: Crores = » One Crore «

  Case Else: Crores = Crores & » Crores «

 End Select

 Select Case Lakhs

  Case «»: Lakhs = «»

  Case «One»: Lakhs = » One Lakh «

  Case Else: Lakhs = Lakhs & » Lakhs «

 End Select

 Select Case Rupees

  Case «»: Rupees = «Zero «

  Case «One»: Rupees = «One «

  Case Else:

  Rupees = Rupees

 End Select

 Select Case Paise

  Case «»: Paise = » and Paise Zero Only «

  Case «One»: Paise = » and Paise One Only «

  Case Else: Paise = » and Paise » & Paise & » Only «

 End Select

‘creating the string of words to translate number into words

 NUM_TO_IND_RUPEE_WORD = IIf(incRupees, «Rupees «, «») & Crores & _ Lakhs & Rupees & Paise

End Function

‘ Converts a number from 100-999 into text

Function GetHundreds(ByVal MyNumber)

 Dim Result As String

 If Val(MyNumber) = 0 Then Exit Function

 MyNumber = Right(«000» & MyNumber, 3)

 ‘ Convert the hundreds place.

 If Mid(MyNumber, 1, 1) <> «0» Then

 Result = GetDigit(Mid(MyNumber, 1, 1)) & » Hundred «

 End If

 ‘ Convert the tens and ones place.

 If Mid(MyNumber, 2, 1) <> «0» Then

  Result = Result & GetTens(Mid(MyNumber, 2))

 Else

  Result = Result & GetDigit(Mid(MyNumber, 3))

 End If

 GetHundreds = Result

End Function

‘ Converts a number from 10 to 99 into text.

Function GetTens(TensText)

 Dim Result As String

 Result = «» ‘ Null out the temporary function value.

 If Val(Left(TensText, 1)) = 1 Then ‘ If value between 10-19…

 Select Case Val(TensText)

  Case 10: Result = «Ten»

  Case 11: Result = «Eleven»

  Case 12: Result = «Twelve»

  Case 13: Result = «Thirteen»

  Case 14: Result = «Fourteen»

  Case 15: Result = «Fifteen»

  Case 16: Result = «Sixteen»

  Case 17: Result = «Seventeen»

  Case 18: Result = «Eighteen»

  Case 19: Result = «Nineteen»

  Case Else

 End Select

 Else ‘ If value between 20-99…

  Select Case Val(Left(TensText, 1))

  Case 2: Result = «Twenty «

  Case 3: Result = «Thirty «

  Case 4: Result = «Forty «

  Case 5: Result = «Fifty «

  Case 6: Result = «Sixty «

  Case 7: Result = «Seventy «

  Case 8: Result = «Eighty «

  Case 9: Result = «Ninety «

 Case Else

 End Select

 Result = Result & GetDigit _

 (Right(TensText, 1)) ‘ Retrieve ones place.

 End If

 GetTens = Result

End Function

‘ Converts a number from 1 to 9 into text.

Function GetDigit(Digit)

 Select Case Val(Digit)

  Case 1: GetDigit = «One»

  Case 2: GetDigit = «Two»

  Case 3: GetDigit = «Three»

  Case 4: GetDigit = «Four»

  Case 5: GetDigit = «Five»

  Case 6: GetDigit = «Six»

  Case 7: GetDigit = «Seven»

  Case 8: GetDigit = «Eight»

  Case 9: GetDigit = «Nine»

  Case Else: GetDigit = «»

 End Select

End Function

The above code will get the result in correct format. Now make your own customized function.

To ensure that your CONCATENATE formulas always deliver the correct results, remember the following simple rules:

Excel CONCATENATE function requires at least one «text» argument to work.

Hope this article about How to Combine Text and a Formatted Date in Excel is explanatory. Find more articles on calculating values and related Excel formulas here. If you liked our blogs, share them with your friends on Facebook. And also you can follow us on Twitter and Facebook. We would love to hear from you, do let us know how we can improve, complement or innovate our work and make it better for you. Write to us at info@exceltip.com.

Excel REPLACE vs SUBSTITUTE function: The REPLACE and SUBSTITUTE functions are the most misunderstood functions. To find and replace a given text we use the SUBSTITUTE function. Where REPLACE is used to replace a number of characters in a string.

Converts decimal Seconds into time format : As we know that time in excel is treated as numbers. Hours, Minutes, and Seconds are treated as decimal numbers. So when we have seconds as numbers, how do we convert into time format? This article got it covered.

Calculate Minutes Between Dates & Time in Excel : calculating the time difference is quite easy. Just need to subtract the start time from the end time. Learn more about this formula clicking the link

How to use the VLOOKUP Function in Excel : This is one of the most used and popular functions of excel that is used to lookup value from different ranges and sheets. 

How to use the IF Function in Excel : The IF statement in Excel checks the condition and returns a specific value if the condition is TRUE or returns another specific value if FALSE.

How to use the COUNTIF Function in Excel : Count values with conditions using this amazing function. You don’t need to filter your data to count specific values. Countif function is essential to prepare your dashboard.

Like this post? Please share to your friends:
  • Text will not wrap in word table
  • Text will not justify word
  • Text width microsoft word
  • Text vocabulary word of the day
  • Text variables in word