Datetime from string excel

Excel for Microsoft 365 Excel for the web Excel 2021 Excel 2019 Excel 2016 Excel 2013 Excel 2010 Excel 2007 More…Less

Occasionally, dates may become formatted and stored in cells as text. For example, you may have entered a date in a cell that was formatted as text, or the data might have been imported or pasted from an external data source as text.

Dates that are formatted as text are left-aligned in a cell (instead of right-aligned). When Error Checking is enabled, text dates with two-digit years might also be marked with an error indicator: Cell with a formula error .

Because Error Checking in Excel can identify text-formatted dates with two-digit years, you can use the automatic correction options to convert them to date-formatted dates. You can use the DATEVALUE function to convert most other types of text dates to dates.

If you import data into Excel from another source, or if you enter dates with two-digit years into cells that were previously formatted as text, you may see a small green triangle in the upper-left corner of the cell. This error indicator tells you that the date is stored as text, as shown in this example.

Cells with green error indicator in upper-left corner

You can use the Error Indicator to convert dates from text to date format.

Notes: First, ensure that Error Checking is enabled in Excel. To do that:

  1. Click File > Options > Formulas.

    In Excel 2007, click the Microsoft Office button Office button image , then click Excel Options > Formulas.

  2. In Error Checking, check Enable background error checking. Any error that is found, will be marked with a triangle in the top-left corner of the cell.

  3. Under Error checking rules, select Cells containing years represented as 2 digits.

Follow this procedure to convert the text-formatted date to a normal date:

  1. On the worksheet, select any single cell or range of adjacent cells that has an error indicator in the upper-left corner. For more information, see Select cells, ranges, rows, or columns on a worksheet.

    Tip: To cancel a selection of cells, click any cell on the worksheet.

  2. Click the error button that appears near the selected cell(s).

    Error button

     

  3. On the menu, click either Convert XX to 20XX or Convert XX to 19XX. If you want to dismiss the error indicator without converting the number, click Ignore Error.

    Commands for converting dates

     

    The text dates with two-digit years convert to standard dates with four-digit years.

    Converted dates

     

    Once you have converted the cells from text-formatted dates, you can change the way the dates appear in the cells by applying date formatting.

If your worksheet has dates that were perhaps imported or pasted that end up looking like a series of numbers like in the picture below, you probably would want to reformat them so they appear as either short or long dates. The date format will also be more useful if you want to filter, sort, or use it in date calculations.

column of dates in text format

  1. Select the cell, cell range, or column that you want to reformat.

  2. Click Number Format and pick the date format you want.

The Short Date format looks like this:

change data to short date format from ribbon

The Long Date includes more information like in this picture:

button on the ribbon to change to long date format

To convert a text date in a cell to a serial number, use the DATEVALUE function. Then copy the formula, select the cells that contain the text dates, and use Paste Special to apply a date format to them.

Follow these steps:

  1. Select a blank cell and verify that its number format is General.

  2. In the blank cell:

    1. Enter =DATEVALUE(

    2. Click the cell that contains the text-formatted date that you want to convert.

    3. Enter )

    4. Press ENTER, and the DATEVALUE function returns the serial number of the date that is represented by the text date.
       

      What is an Excel serial number?

      Excel stores dates as sequential serial numbers so that they can be used in calculations. By default, January 1, 1900, is serial number 1, and January 1, 2008, is serial number 39448 because it is 39,448 days after January 1, 1900.To copy the conversion formula into a range of contiguous cells, select the cell containing the formula that you entered, and then drag the fill handle Fill handle across a range of empty cells that matches in size the range of cells that contain text dates.

  3. After you drag the fill handle, you should have a range of cells with serial numbers that corresponds to the range of cells that contain text dates.

  4. Select the cell or range of cells that contains the serial numbers, and then on the Home tab, in the Clipboard group, click Copy.

    Keyboard shortcut:  You can also press CTRL+C.

  5. Select the cell or range of cells that contains the text dates, and then on the Home tab, in the Clipboard group, click the arrow below Paste, and then click Paste Special.

  6. In the Paste Special dialog box, under Paste, select Values, and then click OK.

  7. On the Home tab, click the popup window launcher next to Number.

  8. In the Category box, click Date, and then click the date format that you want in the Type list.

  9. To delete the serial numbers after all of the dates are converted successfully, select the cells that contain them, and then press DELETE.

Need more help?

You can always ask an expert in the Excel Tech Community or get support in the Answers community.

Need more help?

I have 100.000 rows of data in Excel. Some of the fields are dates, but the fields in Excel are as text. I need these fields in number format including both dates AND time (e.g. 21.10.2011 13:10:50). Formatting the cells doesn’t work because that doesn’t change the datatype. I can pick out the date and time with formulas but not get them in the same cell.

So what I am looking for is the formula to calculate the number representation of a date (the one you see if you format a date as a number).

Lance Roberts's user avatar

Lance Roberts

22.2k32 gold badges112 silver badges129 bronze badges

asked Apr 18, 2013 at 17:14

Machman's user avatar

1

Have you tried the =DateValue() function?

To include time value, just add the functions together:

=DateValue(A1)+TimeValue(A1)

answered Apr 18, 2013 at 17:16

David Zemens's user avatar

David ZemensDavid Zemens

52.8k11 gold badges79 silver badges129 bronze badges

3

To accomodate both data scenarios you have, you will want to use this:

datevalue(text(a2,"mm/dd/yyyy"))

That will give you the date number representation for a cell that Excel has in date, or in text datatype.

answered Apr 18, 2013 at 17:29

Alan Waage's user avatar

Alan WaageAlan Waage

6034 silver badges12 bronze badges

1

I was struggling with this for some time and after some help on a post I was able to come up with this formula =(DATEVALUE(LEFT(XX,10)))+(TIMEVALUE(MID(XX,12,5))) where XX is the cell in reference.

I’ve come across many other forums with people asking the same thing and this, to me, seems to be the simplest answer. What this will do is return text that is copied in from this format 2014/11/20 11:53 EST and turn it in to a Date/Time format so it can be sorted oldest to newest. It works with short date/long date and if you want the time just format the cell to display time and it will show. Hope this helps anyone who goes searching around like I did.

vjdhama's user avatar

vjdhama

4,8505 gold badges33 silver badges47 bronze badges

answered Nov 26, 2014 at 7:43

LuckoftheLefty's user avatar

The best solution is using DATE() function and extracting yy, mm, and dd from the string with RIGHT(), MID() and LEFT() functions, the final will be some DATE(LEFT(),MID(),RIGHT()), details here

answered Nov 14, 2017 at 15:29

Dan's user avatar

It is common to import data from other sources in Excel and it is also common to not get properly formatted data. For example, most of the time when we get data from other sources the date, time and numeric values are in text format. They need to be converted in the proper format. It is easy to convert numbers into excel numbers. But converting string into excel datetime may need a little bit of effort. 

In this article, we will learn how you can convert text formatted date and time in excel date and time.

Generic Formula

Datetime_string: This is the reference of the string that contains the date and time.

The main functions in this generic formula are DATEVALUE and TIMEVALUE. Other functions are used to extract date string and time string if they are combined into one string. And yes, the cell that contains this formula should be formatted into datetime format otherwise you will see serial numbers that may confuse you.

Let’s see some examples to make things clear.

Example: Convert Imported Date and Time into Excel Datetime

Here we have date and time combined into one string. We need to extract date and time separately and convert them into excel datetime.

Note that I have formatted C3 as a date so that the results I get are converted into dates and I don’t see a fractional number. (Secrets of excel date and time).

So let’s write the formula:

And it returns the date and time that excel considers as datetime, not string.

If you don’t change the cell formatting, this is what your result will look like.

This isn’t wrong. It is the serial number that represents that date and time. If you don’t know how the date and time are perceived by Excel, you can get complete clarity here.

How does it work?

This is simple. We use extraction techniques to extract date and time strings. Here we have LEFT(B3,10). This returns 10 characters from the left of the string in B3. Which is «12/02/2020». Now this string is supplied to the DATEVALUE function. And DATEVALUE converts the date string into its value. Hence we get 44167.

Similarly, we get time value using  MID function (for extraction) and TIMEVALUE function.

The MID function returns 8 characters from the 12th  position in string. Which is «12:23:00». This string is supplied to TIMEVALUE function that returns .51597.

Finally we add these numbers up. This gives us the number 44167.51597. When we convert the cell formatting to MM/DD/YYYY HH:MM AM/PM format we get the exact datetime.

In the above example, we had date and time concatenated together as a string. If you just have date as string without any extra text or string, you can use the DATEVALUE function alone to get the Date converted into excel date.

If you just have time as a string use the TIMEVALUE function

You can read about these functions by clicking on the function name in the formula.

So yeah guys, this is how you convert a date and time string into excel date time value. I hope this was helpful. If you have any doubts regarding this article or have any other query related Excel/VBA, ask me in the comment section below. I will be happy to help you.

Related Articles:

Convert Date and Time from GMT to CST : While working on Excel reports and Excel dashboards in Microsoft Excel, we need to convert Date and Time. In addition, we need to get the difference in timings in Microsoft Excel. 

How to Convert Time to Decimal in Excel : We need to convert the time figures into decimals using a spreadsheet in Excel 2016. We can manipulate time in excel 2010, 2013 and 2016 using the function CONVERT, HOUR and MINUTE.

How to Convert date to text in Excel : In this article we learned how to convert text into date, but how do you convert an excel date into text. To convert an excel date into text we have a few techniques.

Converting Month Name to a Number in Microsoft Excel : When it comes to reports numbers are better than text. In Excel if you want to convert month names into numbers (1-12). Using the function DATEVALUE and MONTH you can easily convert months into numbers.

Excel convert decimal Seconds into time format : As we know, 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 them into time format? This article got it covered.

Popular Articles:

50 Excel Shortcuts to Increase Your Productivity | Get faster at your task. These 50 shortcuts will make you work even faster on Excel.

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

How to use the Excel COUNTIF Function| 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.

How to Use the SUMIF Function in Excel | This is another dashboard essential function. This helps you sum up values on specific conditions.

The DATE function creates a valid date using three arguments: year, month, and day:

=DATE(year,month,day)

In cell C6, we use the LEFT, MID, and RIGHT functions to extract each of these components from a text string, and feed the results into the DATE function:

=DATE(LEFT(B6,4),MID(B6,5,2),RIGHT(B6,2))

The LEFT function extracts the leftmost 4 characters for year, the MID function extracts characters in positions 5-6 for month, and the RIGHT function extracts the rightmost 2 characters as day. Each result is returned directly to the DATE function. The final result is a proper Excel date that can be formatted any way you like.

This approach can be customized as needed. For example, the unrecognized date format in row 8 is dd.mm.yyyy and the formula in C8 is:

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

Long form text

Sometimes you may have dates in a longer form like «Apr 11 2020 08:43:13″ that Excel does not recognize properly. In this case, you may be able to adjust the string in a way that allows Excel to correctly recognize the date with the SUBSTITUTE function. The formula below replaces the second instance of a space (» «) with a comma and space («, «):

=SUBSTITUTE(A2," ",", ",2)+0 // add comma after month

Once we add the comma after the month name, Excel will understand the date, but it still needs a little «kick». That’s why we add zero at the end. The math operation causes Excel to try and convert the string to a number. When successful, this will result in a valid Excel date. Note you may need to apply date number formatting to display the date correctly.

Without formulas

Before you use a formula to manually parse and construct a date from text, try one of the fixes below. The first option uses a math operation to «nudge» Excel a bit and force it to try and evaluate the text as a number. Because Excel dates are in fact numbers, this can often do the trick. You may need to apply a date format if the operations succeeds.

Add zero to fix dates

Sometimes, you’ll encounter dates in a text format that Excel should recognize. In this case, you might be able to force Excel to convert the text values into dates by adding zero to the value. When you add zero, Excel will try to coerce text values to numbers. Since dates are just numbers, this trick is a great way to convert dates in text format that Excel really should understand.

To convert dates in place by adding zero, try Paste Special:

  1. Enter zero (0) in an unused cell and copy to the clipboard
  2. Select the problematic dates
  3. Paste Special > Values > Add
  4. Apply a date format (if needed)

You can also add zero in a formula like this:

=A1+0

where A1 contains an unrecognized date.

Text to columns to fix dates

Another way to get Excel to recognize dates is to use the Text to Columns Feature:

Select the column of dates, then try Data > Text to columns > Fixed > Finish

If Excel recognizes the dates, it will fix them all in one step.

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))

You might find yourself working with spreadsheets that have jumbled up data. For example, a single cell holds up all of your information instead of distributing it among different cells or adding columns. You might also come across data from another system where Excel does not easily recognize the dates. It can be hard when you have to extract a date from a string of texts. Sometimes you find it a challenge as the date might even be in the wrong format and position in the first place.

So, how do we extract a date from a text string? In this article, we are going to explain to you the steps to achieving this.

Method 1: Use Find & Replace

We make mistakes by placing full stop characters to separate the year, month, and day. Doing so is a mistake as Excel will not recognize the entry as a date but as a text. You can solve this using the find and replace tool, replace the dots with slashes where Excel will automatically recognize said values as dates. Here’s what to do;

1. Select the columns to convert the texts to date values.

2. Click the Home tab and then the Find & Select option.

3. In the open window, select Replace option.

4. In the ‘Find what’ fields, type the full stop icon, while in the ‘Replace with’ field, type the slash icon.

5. Lastly, click Replace All. All full stops will be converted to slashes by Excel.

Method 2: Use Text to Columns

1. Select your range of values

2. Go to the Data tab in the main menu ribbon.

3. Select Text to Columns. A display wizard will appear. Click ‘Next’ on the first two steps. In the third step, choose the Date field and the date format in the drop-down list provided.

Once you click finish, the data will be extracted to the next empty  cell

Method 3: Using Excel MID, SEARCH & DATEVALUE Functions

1. Type the formula below in the cell you are working on (e.g. Cell C5) and hit Enter.

                        =DATEVALUE(MID($B5,SEARCH(“/??/”,$B5,1)-2,10))

2. As a result, you get a numeric number since excel stores dates as numbers.

3. The number in the previous step is in General Number format and is to be converted into Date format. So, select Cell C5 and press Ctrl +1 to bring the Format Cells dialog.

4. When the Format Cells dialog pops up, go to the Number tab, then select Category: Date and choose the date Type, and press OK.

5. When the Date Number format is applied, use the Fill Handle (+) to separate the data generated from the rest of the texts.

6. When a date included in the string is not a valid date, excel returns the #VALUE!

7. To avoid encountering the error, the above formula is passed within the IFERROR function and the final formula used is:

          =IFERROR(DATEVALUE(MID(B5,SEARCH(“/??/”,B5,1)-2,10)),””)

8. Therefore IFERROR function returns a blank when the result is an error.

Method 4: Using a combination of Excel INDIRECT, LEN, MIN, FIND & ROW Functions

1. In Cell C5, type the below formula and press Enter.

=MID(B5,MIN(IFERROR(MIN(FIND({0,1,2,3,4,5,6,7,8,9},B5&”0123456789”,1)),LEN(B5)+1)),LOOKUP(1,0*MID(B5,ROW(INDIRECT(“1:”&LEN(B5)))) + 1 – MIN(IFERROR(MIN(FIND({0,1,2,3,4,5,6,7,8,9},B5&”0123456789”,1)),LEN(B5)+1)))

2. As a result, the date part of the text string in Cell B5 is separated. Now use the Fill Handle (+) to copy the formula used in the above step to the rest remainder of the cells.

Method 3: Using Excel VBA

This method applies the VBA User Defined Function to separate the date from the text.

1. First, access the VBA window by pressing Alt + F11.

2. When the VBA window pops up, right-click on VBAProject > Insert >Module.

3. A new module will be created. Type the below code in it.


Function DateSeparate(st As String)
On Error GoTo eH
Dim j As Integer, d As Date, ar() As String, tmp As String
d = 0
ar = Split(st)
For j = LBound(ar) To UBound(ar)
tmp = ar(j)
If IsDate(tmp) And Len(tmp) > 5 Then
d = DateValue(tmp)
Exit For
End If
Next j
cont:
DateSeparate = d
Exit Function
eH:
d = 0
Resume cont
End Function 

4. Now go to the worksheet containing the text string just as the UDF was created and type in the formula =DateSeparate(B5) in Cell C5 and press Enter.

5. However, in a case of a text with an irregular date format, we get no valid date. To avoid the problem, the IF function is added to the formula.

                        =IF(DateSeparate(B5)=0,””,DateSeparate(B5))

Conclusion

This article has provided ways of extracting data from a string of text. You can choose either of the methods to modify your spreadsheet and still get the same result.

See all How-To Articles

This tutorial demonstrates how to convert a string in a cell to a date by using Text to Columns in Excel and Google Sheets.

convert string to date final data

► Click here to jump to the DATEVALUE Function section of this tutorial. It focuses on Google Sheets, but the same info applies to Excel.
► Click here to learn more about using the DATEVALUE Function in Excel.

Convert a Text String to a Date

If you have dates formatted as text, you can easily convert them to date format using the Text to Columns functionality. This is often the case when you export data from another system. The data don’t usually have the appropriate formats. Say you have the list of dates shown below in Column B, all formatted as text.

convert string to date initial data 1

The goal is to get dates from Column B formatted consistently as dates (M/D/YYYY) in Column C.

  1. Select the data range (B2:B7) and in the Ribbon, go to Data > Text to Columns.

convert string to date text to columns

  1. In Step 1 of the Text to Columns Wizard, leave the default option (Delimited), and click Next.

convert string to date text to columns 1

  1. In Step 2, uncheck all delimiters, and click Next.

convert string to date text to columns 2

  1. In the last step of the wizard, choose Date (MDY). In the Destination box, enter the cell where you want to position the new data (C2), and click Finish.
    With Date chosen, Excel recognizes dates from the given text and formats them appropriately. The default date format is M/D/YYYY, so leave it as is.

convert string to date text to columns 3

Finally, in Column C, you get all dates from Column B formatted as dates, rather than text.

convert string to date final data

Convert a Text String to a Date in Google Sheets

In Google Sheets, there is no option to get dates from text cells using Text to Columns. You have to use the DATEVALUE Function to convert strings to dates.

Note: The DATEVALUE Function is also available in Excel and works in exactly the same way as explained below.

  1. In the cell C2, type the formula:
=DATEVALUE(B2)

google sheets convert string to date datevalue function

The result of the formula is 44,280.
The DATEVALUE Function returns a number for a given date. In Excel, dates are stored as numbers, starting from 1/1/1900. Therefore, 3/25/2021 is actually the 44,280th day after 1/1/1900.

  1. Position the cursor in the bottom-right corner of C2 until a black cross appears, and drag it through the end of the data range (C7).

google sheets convert string to date datevalue function 2

As a result of this step, the formula from C2 is copied to the range C3:C7.

google sheets convert string to date datevalue function 3

Note: The DATEVALUE Function recognizes only strings that have the date format MM/DD/YYYY. As you can see, the formula in cells C3 and C5 returns a value error (#VALUE!), since text in B3 and B5 isn’t in the right format.

  1. Now format values in Column C as dates to display dates in a proper format. Select all cells in a range (C2:C7), and in the Menu, go to Format > Number > Date.

google sheets convert string to date datevalue function 4

As a result, all text cells from Column B (that have dates with valid formats) are now copied to Column C, and formatted as dates.

Note: For this specific example, find and replace all periods with slashes to get rid of the errors.

google sheets convert string to date datevalue function final

In this guide, we’re going to show you how to extract date from string in Excel by using formulas and VBA.

Download Macro-Free Workbook

Download Workbook

Note that, there isn’t a single formula or approach that can handle all scenarios. Extracting dates from strings that is not following a specific pattern is one of the few things Excel cannot handle. You almost need an AI to be able to encapsulate every possible scenario. The good thing is that we are going to offer you multiple ways to parse the date.

Data

We have generated strings that included dates using slash (/) as day-month-year separator and using US-type (month/day/year) dates. Thus, if your date format is different, you may see errors (empty cells because of IFERROR functions) after opening our file. Update the dates according to your localization settings. Also, do not forget to update the slash characters if your data includes dates with other separators like dot (.) or hyphen (-).

Formula for extracting date from string

The logic behind the formulas we will introduce is to locate the pattern that resembles a date. Once the potential date value’s location is found, we can parse it easily.

The tricky part is to select a correct pattern which is suitable with your raw data. A date can be in many forms:

  • 01/07/2022
  • 1/7/2022
  • 1/7/22
  • 1/12/2022
  • 12/1/2022
  • 12/1
  • 12/2022

If your raw data contains more than one or two patterns the formula solution may not work unless you do not want to create extremely long formulas.

In our sample formula, we used «01/07/2022» format. Thus, we assume the date values in the data to follow the rules below:

  • US Date format
  • Month and day are two digits
  • Year uses four digits
  • Each unit is separated by slash «/»
  • A date contains 10 characters including delimiters

Based on these assumptions, we can use «/??/» keyword with the SEARCH function to locate the date. The SEARCH function can use the wildcards to locate a pattern instead of an exact string. Because a question mark (?) represents a single character, «/??/» refers 2 characters between slashes just like the day part of a date.

The SEARCH function returns the position number where the keyword starts if there is a matching string.

Change the pattern keyword based on your data. For example, «.??.» or ??-????

Subtract the position by 2 to find where the date starts.

Once the date is located, you can use the MID function to parse it. The MID function needs the position of the string you want to parse and its length. Because we assume the date format is «mm/dd/yyyy», the length will be 10.

=MID(<data>,SEARCH(«/??/»,<data>,1)-2,<date length>)

Although, the formula looks like its working, it will return any characters matching the pattern i.e. letters.

This is where the DATEVALUE function comes handy. The function can convert text-based date/time values into actual dates. The function returns #VALUE! error if the supplied text is not a valid date. You can use the DATEVALUE function to verify dates. The IFERROR function can wrap the formula to cover scenarios without date.

=IFERROR(DATEVALUE(MID(<data>,SEARCH(«/??/»,<data>,1)-2,<date length>)),»»)

Although this formula is suitable for our example, it’s obvious that it will fail for others. A few examples:

  • A single-digit month date without a space in front: cells C6, C9
  • A text containing similar string before the actual date: cell C8
  • Single-digit month and days: cells between C19 and C25
  • Double-digit years: cells between C26 and C32

How to extract date from string in Excel w Formula

Using VBA for extracting date from string

An alternative to the Excel formulas is to create your own function by using VBA. The VBA-based functions, also known as user defined functions (UDF), can be used as regular formulas once they are written and saved properly.

VBA has two dedicated methods which give a particular advantage for extracting a date from a string.

  1. The Split method can separate words or strings separated by spaces.
  2. The DateValue method can validate dates better than its formula counterpart.

Obviously, this method is not foolproof neither. The date values should be separated from other text by a space character. On the other hand, you are not limited with a certain pattern. Thus, number of digits in units are not significant.

You can copy and paste the following code into a module and start using it right away. Just do not forget to save your Excel file as an Excel Macro-Enabled Workbook (XLSM) rather than a regular workbook.

Function ExtractDate(str As String)
    
    On Error GoTo errHandler
    Dim i As Integer, dt As Date, arr() As String, temp As String
    
    dt = 0
    arr = Split(str)
    
    For i = LBound(arr) To UBound(arr)
        temp = arr(i)
        If IsDate(temp) And Len(temp) > 5 Then
            dt = DateValue(temp)
            Exit For
        End If
    Next i

cont:
    ExtractDate = dt
    Exit Function
    
errHandler:
    dt = 0
    Resume cont
End Function

How to extract date from string in Excel w VBA

Once you paste the code, use it in your worksheet by giving a reference to the data cell.

=IF(ExtractDate(<data>)=0,»»,ExtractDate(<data>))

The equals to zero (0) condition is to avoid zero (0) values. Otherwise, the function will return zero (0) when it cannot find a valid date.

How to extract date from string in Excel w UDF

As you can see either approach is far from perfection. However, you have more than one option to extract date from string.

Понравилась статья? Поделить с друзьями:
  • Dates as text in excel
  • Dates and times in excel vba
  • Dates and months in excel
  • Datediff in excel vba
  • Datediff excel нет в эксель