How to separate date-time stamp into 2 columns? - excel

I have a spreadsheet with a column containing two different datetime formats that I'm trying to split into a standardised column. The two formats are as such:
21/09/2017 7:39
14/07/17 13:47
I've tried splitting out the datetime components individually, but it appears the YEAR function doesn't like parsing the two digit dates. As a ghetto workaround, I've done a find and replace, but this isn't sustainable. Any excel geniuses out there have any ideas or functions I should be looking at?
Cheers

Since you wanted a VBA response to your question, here it is.
You will need to make adjustments to your range, as this is only going to pull off of A1 (you didn't specify the original range with the text dates, nor the ranges of the new date and times).
Option Explicit
Sub SplitDateAndTime()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets(1)
Dim RawVal As String, RawDate As String, RawTime As String
RawVal = ws.Range("A1").Value
RawDate = Split(RawVal, " ")(0)
RawTime = Split(RawVal, " ")(1)
Dim NewDate As Date, NewTime As Date
NewDate = CDate(RawDate)
NewTime = CDate(RawTime)
ws.Range("A1") = NewDate
ws.Range("B1") = NewTime
End Sub

Please note this formula assumes all of your dates will be after the year 2000. If that's not true, let me know and I'll figure something else out.
It looks like your first date is being recognised as a proper datetime, while your second is a text value.
Here is what I've worked out:
There is an =IFERROR formula in both the Date and Time columns. The first formula in each works on the datetime format, and the second works on the text format and can be dragged down to work on any cell reference.
This is the formula in B1:
=IFERROR(DATE(TEXT(A2,"yyyy"),TEXT(A2,"mm"),TEXT(A2,"dd")), DATE(MID(MID(A2,FIND("/",A2)+1,5),FIND("/",MID(A2,FIND("/",A2)+1,5))+1,2)+2000,MID(A2,FIND("/",A2)+1,2),LEFT(A2,FIND("/",A2)-1)))
And this is the formula in C1:
=IFERROR(TIME(TEXT(A2,"hh"),TEXT(A2,"mm"),0),TIME(LEFT(MID(A2,FIND(":",A2)-2,5),FIND(":",MID(A2,FIND(":",A2)-2,5))-1),MID(MID(A2,FIND(":",A2)-2,5),FIND(":",MID(A2,FIND(":",A2)-2,5))+1,256),0))

To get the Date assuming that your data in on column A
=DATEVALUE(MID(A1,1,FIND(" ",A1)-1))
T0 get the Time assuming that your data in on column A
=TIMEVALUE(MID(A1,FIND(" ",A1)+1,5))

Related

Using Match to find a date in a list of dates yields different answers depending on the formatting of the dates

I have a list of dates (work days, no weekends) on column A that is sorted in ascending order. The column has a string header that reads "Dates." The format of the column is m/d/yyyy. The first date is 5/28/1998 on cell A2 and the last date is 2/9/2023 on cell A6216.
I also have a date on cell AG275 with the date 6/28/1999. I need to find the row for that date on column A.
This code has no problem finding the date, as long as both column A and cell AG275 are formatted as General. In that case, cell AG275 reads as 36337 and the answer (variable a in the code below) returns 275, which indeed is the row where 36337 is.
Sub findDate()
Dim dateToFind
Dim arr()
Dim Rng As Range
dateToFind = Cells(275, "ag").Value
Set Rng = Worksheets("calcSheet").Range("A1:A6216")
arr = Rng
a = WorksheetFunction.Match(dateToFind, arr, 1)
End Sub
The problem is that if both column A and cell AG275 are formatted as short date then the code answer (variable a) is not 275 but 1530, which is 6/25/2004, which in General formatting is 38163 (the following date on cell A1531 is 6/28/2004).
I suppose I could add code to reformat everything before starting the code and work with numbers instead of dates, but I'd rather not do that and work with the given dates. How can I get the right answer if everything is formatted as short dates?
I suspect the problem may have to do with the way I am declaring the variables and the array, but I have tried multiple variations of declaring as Date, as Variant, as Long and as Integer to no avail. I also tried, as I read in other related posts,
dateToFind = CDate(Cells(275, "ag").Value)
and
dateToFind = CLng(CDate(Cells(275, "ag").Value))
but neither one helped me get any closer to a solution. Incidentally the behavior is the same for long dates (mm/dd/yyyy).
If anyone can chime in I would be very grateful. Many thanks
No mater the formatting if the content of the cells are dates and the content of the cell to find is a date, the following will work:
Sub findDate()
Dim dateToFind As Variant
Dim Rng As Range
dateToFind = Cells(275, "ag")
Set Rng = Worksheets("calcSheet").Range("A1:A6216")
a = Application.Match(CLng(dateToFind), Rng, 1)
End Sub

Change String date (DD.MM.YY) to Dateformat(YYYY-MM-DD) in excel

I have nearly 2,00,000 records of data in my excel sheet and I have Date columns as a string like this (dd.mm.yy) I have to convert it into dateformat of (YYYY-MM-DD) .
I tried this -
For the example date string, 1.11.11 , I tried to replace .11 with .2011 but it will also change the month to 1.2011.2011 and my sheet has huge records from 2010 to 2016 .
Example - My cell has this 1.11.11 and i want to convert it to 2011-01-01 (YYYY-MM-DD)
Please help !
Thank you.
Use this to change it to a true date:
=DATE(2000+SUBSTITUTE(RIGHT(A1,2),".",""),SUBSTITUTE(MID(A1,FIND(".",A1)+1,2),".",""),SUBSTITUTE(LEFT(A1,2),".",""))
Then format the output to your desired: YYYY-MM-DD
To do it in place one would need vba.
Select your date cells and run this code.
Sub datechange()
Dim rng As Range
Dim str() As String
For Each rng In Selection
str = Split(rng.Value, ".")
rng.Value = DateSerial(2000 + str(2), str(1), str(0))
Next rng
Selection.NumberFormat = "yyyy-mm-dd"
End Sub
Assuming the values start in A1 AND if they are all truly in the DD.MM.YY (with zeroes (04, 06, etc...)
="20"&RIGHT(A1,2)&"-"&MID(A1,4,1)&"-"&LEFT(A1,2)
Try bellow formula :
=TEXT(SUBSTITUTE(A1,".","/"),"YYYY-MM-DD")
Try this:
select convert(varchar,convert(datetime,'26-July-2018'),105)

Cannot convert date string to datevalue in Excel

I have some dates in a string in a column.
Because the format seems to be M/DD/YYYY I sometimes get a VALUE error when using DATEVALUE.
How can I convert a column to make sure all dates are correct.
For example, the following 2 cells
9/29/2006 12:49:58.956 AM DATEVALUE gives an error
9/12/2008 5:36:59.356 PM DATEVALUE converts to 39791
You need to select the range (just one colunm) with the dates... Go to:
(in Excel 2010)
Data >>> Text to Columns
Inside the dialog box select:
Delimited >>> Next
Just select Tab checkbox.
And heres is the magic!
You need to define the arrangement for your dates...
In the Date field:
Choose the what you need (as you say in your question is M/D/Y)
Destination field:
Make sure that is the same of the data you want to format.
And finish.
The problem you are having is probably that the data is getting interpreted as a general field, and shows up as, say 49:59.0 - which isn't text, which is what Datevalue() expects as input; for both inputs, Datevalue(CellID) words if you prepend the text with a ' - which ensures it is treated as text.
it seems that your system settings use dd/mm/yyyy for short date format. and datevalue function uses this settings, so its try to read the day from the first part of the string and the month from the second part. as in your example 9/29/2006 12:49:58.956 AM there is no month with 29 then it gives error, and in the second example it gives 39791 = 9 december 2008 and NOT 12 september 2008.
If you change the short date format in your system settings to mm/dd/yyyythen datevalue function will work correctly, but this not acceptable, so we need to replace month with day and day with month to get correct date.
I don't know if we can do this with Excel formula but we can do that simply with VBA.
So try this code:
Sub Test()
Dim d1 As Variant, d2 As Variant, td As Date
Dim Rng As Range, CL As Range
Set Rng = Range("A1:A2") ' change this to your range
For Each CL In Rng
d1 = Split(CL.Value, " ")
d2 = Split(d1(0), "/")
td = DateSerial(d2(2), d2(0), d2(1))
CL.Offset(0, 1) = td
CL.Offset(0, 1).NumberFormat = "mm/dd/yyyy" ' change the Date format as you need
'CL.Offset(0, 1).NumberFormat = "dd/mm/yyyy"
Next
End Sub

Removing time from date for an entire data stored in an array

Using Excel VBA, how would I apply the formula Date(year(A1),Month(A1),Day(A1)) to all the dates in an entire column? Currently the data is in date time format (e.g. 30/04/1995 9:35:00 AM) but I want just the date - 30/04/1995.
Currently all of the dates are stored in an array and I have tried Columns(data_column).NumberFormat = "[$-1009]d-mmm-yy;#",
but I have not been successful in removing the time from the dates.
If you want to change the display format of your data while preserving the time information, you can use something like NumberFormat = "mm/dd/yyyy" in cells of a worksheet or chart axis.
Excel stores date/time info as a floating point number. The days are to the left of the decimal and fractions of days (hh:mm:ss) are to the right. If you want to strip out the time information from the underlying data, then convert to Long then back to Date. In VBA (thanks to T.M. for the correction):
DateOnly = CDate(Int(DateTime))
In worksheet formulas just convert to Int and format as you please
DateOnly = INT(DateTime)
Hope that helps
All dates in Excel include time: datetime. It is not possible to store a date only or a time only in a cell. The reason is that Excel stores them as numbers. Anything before the decimal point is the date and anything after the decimal point is the time. So, even if you put the number 42000 in a cell (without anything after the decimal point) and change the format of that cell to date, the value will still be December 27, 2014 (42000 days after December 31, 1899) with an assumed time of zero = 00:00:00 in the morning.
Since all numbers can potentially have something after the decimal point, all dates have time in Excel and all times have dates.
The only thing you can do is: format a cell to show only the date part or the time part or both. So, all you need to do is to hide the time.
If you want to change all dates to have zero after the decimal point then you'll have to loop through the numbers and change all values to INT values.
For intColumn = 1 to 1000
If Sheet1.Cells(1, intColumn).Value2 = vbNullString then Exit For
Sheet1.Cells(1, intColumn).Value2 = Int(Sheet1.Cells(1, intColumn).Value2) ' Do not use CInt but Int only!
next intColumn
Removing time from date for an entire data stored in an array
IMO this question rather asks how to change values directly in an array containing dates including time indications.
Therefore I the following example code just as an addition to the valid solutions above demonstrating how to
get a zero-based 1-dim array from a data column (without loops),
execute the time removals (in a Loop) using VBA's Fix function *) to cut the decimal part of the date value and
(optionally write back the array to any wanted column)
*) Using the CLng instead of Fix(or Int) would round up to the next day any dates with afternoon hours after midday.
Example code
Assumes date values e.g. in column B:B (omitting a title row).
Sub chngDateArray()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("MySheetName") ' << change to your sheet name string
Dim lastRow&, i&, arr
lastRow = ws.Range("B" & ws.Rows.Count).End(xlUp).Row
' [1a] assign dates to (1-based) 2-dim datafield array
arr = ws.Range("B2:B" & lastRow).Value2 ' get date values as numbers
' [1b] rearrange to (0-based) 1-dim array
arr = Application.Transpose(arr): ReDim Preserve arr(0 To UBound(arr) -1) ' make it a "flat" (zero-based) array
' [2] eliminate time portions and reconvert to date
For i = 0 To UBound(arr)
arr(i) = CDate(Fix(arr(i))) ' cut time portions from entire dates
Next i
' Debug.Print Join(arr, "|") ' check in immediate window
' [3] {optional}: write back array to any wanted column (e.g. D:D)
ws.Range("D2").Resize(UBound(arr), 1).Value2 = Application.Transpose(arr)
End Sub
Additional note
Using .Value2 in section [1a] allows to get dates as numbers only. The reconversion to date format in section [2] eventually allows to write back the array data to any wanted column in section [3] without prior column formatting via NumberFormat.
In addition to the above, you should also be able to pull just the date from those strings using either DateValue() or Format() like so:
DateValue("30/04/1995 9:35:00 AM")
Format("30/04/1995 9:35:00 AM", "dd/mm/yyyy")

How can I keep the date format from a VLookup returned value?

I have a sheet whit mixed format data (dates, double, strings, etc.).
I search the value (my_index) in the lookup_range and I want to retrieve the data to change with it a cell in other sheet. It works fine, but when the value returned by VLookup is a date and I set it to the other sheet it looses its date format.
Dim lookup_range As Range
Dim my_index, my_value As Variant
my_value = Application.VLookup(my_index, lookup_range, num_col, False)
Sheets(3).Cells(num_row, last_col_s1 + num_col - 1).Value = my_value
So, when the data in the lookup_range is 02/05/2014 the data showed at sheet-3 looks like 41761.
I need to keep the original data format of the data in the lookup_range.
VLOOKUP doesn't care about the formatting of the data it's returning - it returns data, not formats.
The only way to ensure the same format as the source, is to copy/paste that format, either manually or programmatically.
use this
Sheets(3).Cells(num_row, last_col_s1 + num_col - 1).Value = cdate(my_value)
I had the same problem, and simply reformatted the VLOOKUP cell to also be in date-time format. That fixed my issue. I am not sure how date-time gets translated into a number, but it does.
i faced the same issue. After vlookup, change the format to "ShortDate" format. This will give you what you are looking for.
Excel Formula :
=TEXT(VLOOKUP(Lookup_value,table_array,col_index_num,0),"dd-mm-yyyy")
VBA :
Sub vlookup_code()
Dim table_rng As Range
'FOR THE TIME BEING GIVING A LOOKUP VALUE
look_up_value = "sekar"
'SETTING THE TABLE ARRAY RANGE
Set table_rng = Sheet1.Range("C3").CurrentRegion
'SINCE VLOOKUP WILL GIVE AN ERROR, IF THE LOOKUP VALUE IS NOT PRESENT
'TO HANDLE THIS ERROR, WE USE THE ISERROR STATEMENT
If IsError(Application.vlookup(look_up_value, table_rng, 2, 0)) = False Then
vlook_value = WorksheetFunction.vlookup(look_up_value, table_rng, 2, False)
'CHANGING THE VLOOKUP VALUE FORMAT TO DATE FORMAT
date_format = WorksheetFunction.Text(vlook_value, "dd-mm-yyyy")
End If
End Sub
In Microsoft Office 2016.
Once data copied to the cell. Select the column which needs to be in date format. Right click->format cells, go to Number tab and select date from the drop-down and choose the required date format, data will be converted to date format.

Resources