So I know this question has been asked a couple of times over, but I believe my situation is a bit different (happy to be proven wrong of course!)
Here is the data flow: a user types a date in a date in a form. They then click a button. My macro then takes that date, runs it through the following function:
Function AddWeekDays(StartDate As Long, Days As Long) As Date
Dim i As Long
Dim d As Date
d = StartDate
i = 0
While i < Days
d = DateSerial(Year(d), Month(d), Day(d) + 1)
If Weekday(d, vbMonday) < 6 Then
i = i + 1
End If
Wend
AddWeekDays = d
End Function
Then it formats the date to change it from mm/dd/yyyy to dd/mm/yyyy in the following way:
Dim deadline As Date
Dim deadline_formatted As Date
Dim DateReceived As String
Dim DateConverted As Date
DateReceived = txt_DateReceived.Text
DateConverted = Format(DateReceived, "dd/mm/yyyy")
deadline = AddWeekDays(DateValue((CStr(DateConverted))), 9)
deadline_formatted = Format(deadline, "dd/mm/yyyy")
However, the deadline_formatted value is still coming out in the mm/dd/yyyy format.
As an example, when a user enters 01/05/2017 the program should return deadline_formatted = 12/05/2017, but it returns deadline_formatted = 05/12/2017
I have tried changing the variable type to string to see if that made a difference (it didn't), and have tried directly converting the deadline variable to the required format by using the following code:
deadline = Format(AddWeekDays(DateValue((CStr(DateConverted))), 9),"dd/mm/yyyy")
which still returns the incorrect format.
Can anybody out there suggest either:
How to fix the formatting issue to get the deadline_formatted into the format dd/mm/yyyy
OR
suggest a "workaround" to flip the "dd" with the "mm" (not ideal obviously, but if it works, it works!)
Thanks for any advice!
The best way to solve this issue is to actually change your computer's default date/time format to match the method used by the users. (In comments it is stated that the users are Australians but your company is US-based, so the default is probably currently set to be the USA's "mm/dd/yyyy" format.)
By ensuring that the computers date/time format is correct, it will allow you to process a date as a Date, and it can be stored in Excel cells as a Date, which then allows any of the Australian users to see it displayed as "dd/mm/yyyy" format while a USA-based colleague would see it displayed as "mm/dd/yyyy".
There is a financial risk to your company caused by forcing users to interact with software using an unfamiliar date system, as accidental entering of dates in the wrong formats can lead to major errors downstream, so it is in the company's best interest to allow you to change the settings to be relevant to the users.
It is not directly related to your problem, however I believe it might fix your issues. The manual calculation of adding week days might be the problem here.
There is a built in function to add workdays. You can include/exclude weekends/holidays. The following code replaces your above mentioned code.
Sub AddWeekDays()
Dim deadline As Date, deadline_formatted As Date
deadline = txt_DateReceived.Value
deadline_formatted = Format(Application.WorksheetFunction.WorkDay(deadline, 9), "dd/mm/yyyy")
'debug.print deadline_formatted
End Sub
the result to be String.
Dim deadline As Date
Dim deadline_formatted As String '<~~ change string
Dim DateReceived As String
Dim DateConverted As Date
txt_DateReceived = "01/05/2017"
DateReceived = txt_DateReceived
DateConverted = Format(DateReceived, "dd/mm/yyyy")
'deadline = AddWeekDays(DateValue((CStr(DateConverted))), 9)
deadline = AddWeekDays(CLng(DateConverted), 9) '<~~ change Long
deadline_formatted = Format(deadline, "dd/mm/yyyy")
I wouldn't bother about the regional settings. Instead, make sure that all dates are captured as Date() or Now() values (42123 or 42123.5555). On the output side such values can be presented in any format you wish.
To ensure that dates are entered correctly my preferred way is to use a date picker. If that can't be done make no rules for entering the date at all, working on the presumption that each user will know how to enter a date on his/her machine. Add a date check, like ISDATE(), which will catch some input errors but not all. You don't need to catch all. You only need to teach users how to input dates on their respective PCs.
With this line you don't need anything else.
Range("E:E").TextToColumns FieldInfo:=Array(0, xlDMYFormat)
'1.2.2019 -> 01/02/2019
'2,3,2019 -> 02/03/2019
'3-4-2019 -> 03/04/2019
'4*5*2019 -> 04/05/2019
'5_-6-*2019 -> 05/06/2019
'and so on
Of course you can change the format with
xlMDYFormat
Related
When a date is returned from our UTC server database Windows very helpfully changes the Date to a DateTime (say 23 June 2017 to 2017-06-23 00:00) and then makes an adjustment for the current Time Zone (to, say 2017-06-22 16:00)... For years we have used the code below to convert it back...
About four months ago users running Windows 7 (Windows 10 doesn't seem to be effected) that did not have 'Automatically adjust clock for Daylight Saving Time' checked, or live in a state like Arizona where that option is not available, noticed that reports where returning the date from the day before - our DB is returning the correct date but the conversion is no longer working correctly..
Any suggestions?
Thanks
Public Function LocalDateFormat(ByVal InputDate As Date) As String
Dim vDate As String = InputDate.ToString("d", System.Globalization.CultureInfo.InvariantCulture)
Dim LocalZone As TimeZone = TimeZone.CurrentTimeZone
Dim CurrentOffset As TimeSpan = LocalZone.GetUtcOffset(InputDate)
Dim DayLightSaving As Boolean = LocalZone.IsDaylightSavingTime(InputDate)
Dim CalculatedOffset As New DateTime(InputDate.Ticks, DateTimeKind.Local)
If CurrentOffset.CompareTo(TimeSpan.Zero) < 0 Then
CalculatedOffset -= LocalZone.GetUtcOffset(InputDate)
If DayLightSaving = True Then
CalculatedOffset = CalculatedOffset.AddHours(1)
End If
Else
CalculatedOffset += LocalZone.GetUtcOffset(InputDate)
If DayLightSaving = True Then
CalculatedOffset = CalculatedOffset.AddHours(-1)
End If
End If
InputDate = CalculatedOffset
Dim vCulture As String = System.Globalization.CultureInfo.CurrentCulture.ToString
Dim vReturnDate As String = ""
Select Case vCulture
Case "en-US"
vReturnDate = Format(InputDate, "MM/dd/yyyy")
Case "en-GB"
vReturnDate = Format(InputDate, "dd/MM/yyyy")
Case Else
vReturnDate = Format(InputDate, "dd/MM/yyyy")
End Select
Return vReturnDate
End Function
Your entire function can be re-written as:
Public Function LocalDateFormat(ByVal InputDate As Date) As String
Return InputDate.ToLocalTime().ToShortDateString()
End Function
With the code so small, you may want to rethink whether there's any benefit of having this in a function at all.
As far as why your existing function didn't work properly:
TimeZone.GetUtcOffset already factors in whether DST is in effect or not, though it has some problems with that that are described in the MSDN docs.
You shouldn't be using TimeZone any more at all. If you need to work with time zones, use TimeZoneInfo, or Noda Time. In this case, you don't need either of them, as you're just converting from UTC to local time, which is what DateTime.ToLocalTime does.
This code has some logic that appears to think one should subtract an hour for DST if the offset is positive. Sorry, but DST doesn't work that way - you always add an hour (unless you are in Lord Howe Island, Australia, where you add 30 minutes).
It also seems to think you should add the offset from UTC if its positive and subtract it if its negative. This is essentially an absolute value function, and also incorrect.
All the culture stuff is handled for you by formatting within the current culture. There's no need to do it by hand.
You say it works fine on Windows 10, but I'm sorry - this is bad code that will have errors wherever it is run. Just use the built-in APIs provided by the framework. Don't reinvent the wheel. :)
I want to know what is the format of given date in vbscript?
Example
If the date is 10/08/2015 I want to check whether which format it its?
dd/mm/yyyy or dd/mm/yy
I check so many function is vbs nothing fit for my requirement
The following function might be useful in some situations. It can distinguish between dd/mm/yyyy and mm/dd/yyyy when possible and tells you when not. It does no error checking so would give misleading results if the string is anything other than a valid date in one of those two formats:
Function FormatUsed(dateString)
Dim parts, first, second
parts = Split(dateString, "/")
first = CInt(parts(0))
second = CInt(parts(1))
If first > 12 Then
FormatUsed = "dd/mm/yyyy"
ElseIf second > 12 Then
FormatUsed = "mm/dd/yyyy"
Else
FormatUsed = "??/??/yyyy"
End If
End Function
I want to filter SQL-table between start date and end date, I used before string variable then I use string.format to make the format mm/dd/yyyy, I tried now in VB.net 2015 the following code:
Dim S as String
s=inputbox("Enter Start date")
S=string.format(S,"mm/dd/yyyy")
But it doesn't work, can somebody give me a solution?
You could try this for handling the input value, assuming you only need the date value as a formatted string, since your question is about formatting a date:
Dim S As String
S = InputBox("Enter Start date")
If IsDate(S) = True Then
Dim d As Date = Date.Parse(S)
S = d.ToString("mm/dd/yyyy")
Else
'Handle the non date input here
End If
But I think you should consider #Plutonix comment, since we don't know exactly how you are sending the date to perform the filtering, or how your table fields are defined.
Regards!
I used this code to add months
dtExpiry = DateAdd(DateInterval.Month, intDuration, dtStartDate)
and I also tried this code,
dtExpiry = DateAdd("m", bytDuration, dtMemStartDate)
but every time it just adds Days not months. The date format has to be dd/mm/yyyy. I've changed my PC date format to dd/mm/yyyy but still it keeps adding Days instead of Months.
BTW I'm receiving the duration and startDate from the Main calling program which extract these values from a data file thats in CSV format.
Your code looks ok, but you may have an incorrect data type.
Try this and see if this works:
dtExpiry = DateAdd(DateInterval.Month, intDuration, CDate(dtStartDate))
If that works then check the data type of dtStartDate.
All this can be avoided if you switch Option Strict On, as the code won't compile if dtStartDate is not of type DateTime
Note that you should also be able to do this:
dtexpiry = dtStartDate.AddMonths(intDuration)
This will fail to compile even with Option Strict Off if dtStartDate is not a DateTime so could be a safer option.
Use datetime.tryparse to convert your string to a date, then use as below?
You can also specify a conversion and specifically tell it what is where in the string (m/d/y)
I.e.:
Dim mydate As New Date
mydate = DateTime.ParseExact(datestring, "dd/MM/yyyy", Nothing, DateTimeStyles.NoCurrentDateDefault)
Dim secondDate As New Date
secondDate = mydate.AddMonths(6)
Or am I missing your question?
I'm having a hard time in converting the date from dd-mm-yyyy format to dd/mm/yyyy format.
For Example,
When i enter a date in excel as 25/02/2012 (dd/mm/yyyy), after entering the date if go in the next line it converts the date in the 25-02-2012 (dd-mm-yyyy) format.
what i want to do is that when i enter the date in (dd/mm/yyyy) format in excel it should keep it as it is and should not change it back to (dd-mm-yyyy) format when i go the next cell.
when i enter my date as the current system date my code gives me an error, i am having trouble validating the date i.e. is the date entered is a valid date or not
Sub valid_date()
' ---------------------------------------------------------------------
' Final Code - Trial
' ---------------------------------------------------------------------
Dim d1 As Variant
Dim IssueDate As Variant
Dim str As Variant
d1 = Worksheets("Sheet1").Cells(6, 1).value
MsgBox " The Issue Date format is " & d1
sysdate = Date
MsgBox "System Date is " & sysdate
If IsDateValid(d1) Then ' if date is in dd/mm/yyyy format then print this
If (d1 > sysdate) Then
MsgBox "Invalid date"
End If
End If
End Sub
Function IsDateValid(pdate) As Boolean
IsDateValid = False
Set RegExp = CreateObject("VBScript.RegExp")
' it only matches whether date is in dd/mm/yyyy format or not
'
' [1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1] ---> it allows the DATE from 01 to 31
' [1-9]|0[1-9]|1[0-2] ---> it allows the MONTH from 01 to 12
' 1[9][0-9][0-9]|2[0][0-9][0-9] ---> it allows the YEAR from 1900 to 2099
'
' below is the regular expression for checking the date in dd/mm/yyyy format
RegExp.Pattern = "^([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])[/]([1-9]|0[1-9]|1[0-2])[/](1[9][0-9][0-9]|2[0][0-9][0-9])$"
' check whether the date is in dd/mm/yyyy format or not....
tempdate = RegExp.Test(pdate)
If tempdate Then ' if tempdate is in dd/mm/yyyy format than proceed further
'If isdate(tempdate) Then ' if date is a valid date then proceed further
If isdate(pdate) Then
IsDateValid = True
Else
IsDateValid = False
End If
Else
IsDateValid = False
End If
End Function
i'm using the above mentioned code by using a regular expression to check whether the date is in dd/mm/yyyy format or not
but the problem which i'm facing is that it takes the date in excel as dd-mm-yyyy format whenever i enter the date in dd/mm/yyyy format.
i have updated my code a bit,
i also need one more help when i enter my date as the current system date it gives me error
for example,
when i enter my date as 09/09/2012 (suppose this your current system date) and when i check this date using IsDate method, it gives me an error
i have again edited my code,
Can anyone please help me on this
You don't need VBA/RegEx. Select the cells/columns where you input dates and create a Custom number format: dd/mm/yyyy. Now no matter how you type in a valid date (05-05-2000, 3-1-2010, 14/6-1990, etc.), it should be formatted as dd/mm/yyyy.
And, as Olle points out, you should use the Date object rather than Variant if you are going to be manipulating dates in VBA. This way you're working with the serial number and not a string with potential formatting issues.
First, I suggest you check the regional settings for dates on your computer. If you set it to use the "dd/mm/yyyy" format it will be used by Excel as well and hopefully remove the need for any RegEx VBA-code.
Second, if you do need to use VBA to reformat dates, I strongly suggest you use the Date data type instead of Variants. I also advise you to use Option Explicit at the top of your code and explicitly declare any variables in order to minimize typos and produce better quality code.
Third, I've looked through your code some more and it seems it will never work:
1. Because it is never declared, tempdate is a Variant
2. You assign tempdate to be a boolean, from the result of RegExp.Test(pdate)
3. So when you check IsDate(tempdate) it will always be false, since a boolean can never be a Date.
Again, if you use the Date data type, you can skip the RegEx... :)
I use Adobe online PDF to Excel and dates display correctly as MM/DD/YYYY but when extracting month (=Month()) it returns the DD portion. It is being interpreted as DD/MM/YYYY. I saved the file as a .csv closed and restarted excel and opened the .csv file and the dates were correct MM/DD/YYYY.