I am trying to set / change the DateTimePicker value (using vb.net) but can't work out how to do it.
I have added the control to the page and I have tried using the following code but it doesn't work and I can't work out how to set the value during run-time.
DateTimePicker1.Value = Now.Day & "-" & Now.Month & "-" & Now.Year
The format of the control is set to Long and it looks like this when first loaded:
Tuesday, February 26, 2013
But I can't work out how to change it.
The error I get based on my code above is:
Conversion from string "26-2-2013" to type 'Date' is not valid.
Anyone got any ideas ?
I ended up getting it working by doing the following:
DateTimePicker1.Value = New Date(2013, 2, 26)
I was loading the value wrong.
Add the following code on Form Load Event to set the date time picker value to today:
DateTimePicker1.CustomFormat="dd-MM-yyyy"
DateTimePicker1.Value=Now()
Related
I've written an app which brings in a CSV export from our HR system, loops through all the records and applies the values from the HR system to active directory.
It works a treat, and when running on my machine i get no errors whatsoever.
When running it on one of our servers, where it is ultimately going to live and will be executed by a service account, I get date conversion errors...
System.InvalidCastException: Conversion from string "21/08/2020" to type 'Date' is not valid.
Right at the start of my code I'm defining the region...
Dim ukCulture = New Globalization.CultureInfo("en-GB")
System.Threading.Thread.CurrentThread.CurrentCulture = ukCulture
And if I query current culture at runtime, it shows 'en-GB', so that seems right.
If i write out the date strings, they all look right, and the compare operation is working fine.
The error seems to occur in this section of code...
Dim converted_hr_accountexpiry_timestamp= hr_row(0).Item("Termination Date") & ""
Dim hr_termdate_var() As String = converted_hr_accountexpiry_timestamp.split("/")
updatescript = updatescript.Replace("$x", "'" & hr_termdate_var(0) & "'") _
.Replace("$y", "'" & hr_termdate_var(1) & "'") _
.Replace("$z", "'" & hr_termdate_var(2) & "'")
So for context, this code is building up a powershell script which is executed to make the necessary changes in AD.
The section of that powershell code that we're looking at here is this...
$server = "MyPrimaryDNSServer.FQDN"
$exp = get-date -Day $x -Month $y -Year $z -Hour 00 -Minute 00 -Second 00
$expirydate = $exp.ToUniversalTime().AddDays(1)
It seems clear that its trying to use a US date format, because if the date provided would match an acceptable US date, ie 3/5/2020, then it will accept it and the wrong date will be applied. The error is only thrown when the day (dd) portion of the date would not be accepted as MM on an american format date, ie 31/07/2020.
And to re-iterate; this issue doesnt happen on my machine, only on the server that will eventually execute the application. I've been through all the region settings on that device itself and everything is set to united kingdom, with the correct dd/MM/yyyy formats for dates.
I'm at a total loss on this one and pulling out what little hair i have left.
Any suggestions/help appriciated!
EDIT 1:
This is the full exception, minus the users name obvs...
Error with account : Joe Bloggs (1010245)
System.InvalidCastException: Conversion from string "24/07/2020" to type 'Date' is not valid.
at Microsoft.VisualBasic.CompilerServices.Conversions.ToDate(String Value)
at Microsoft.VisualBasic.CompilerServices.Operators.CompareObject2(Object Left, Object Right, Boolean TextCompare)
at Microsoft.VisualBasic.CompilerServices.Operators.CompareObjectEqual(Object Left, Object Right, Boolean TextCompare)
at Atlas.Main.GetAccountsWithUpdates()
EDIT 2:
So it looks like there are two errors occuring, which is why I couldnt find it by commenting each related line out in turn.
This is definately one of the erroring lines...
converted_ad_expiry_timestamp = converted_ad_expiry_timestamp.ToString("dd/MM/yyyy").Split(" ")(0)
The value returned is a datetime not a date, so i use tostring and split it on the space to grab just the date portion.
The second error seems to occur in here...
If Not (converted_hr_expiry_timestamp = converted_ad_expiry_timestamp) Then updateme = True : If (hr_row(0).Item("Termination Date")) = "" Then account_expiration_date = "$null" Else account_expiration_date = converted_hr_expiry_timestamp
It looks like the problem revolves around converted_ad_expiry_timestamp which seems to be a Date (the VB type is an alias for a .NET DateTime). You put it into a specific localized format via converted_ad_expiry_timestamp.ToString("dd/MM/yyyy") and then rely on automated conversion to turn it back into a Date. The way to avoid the problem you see here (where the automated conversion uses the system locale to decide the format) is to use one of the Parse or ParseExact family to control the conversion yourself. With Parse, you can specify the locale to use, or with ParseExact you can specify the format.
Similarly, when you attempt to compare them in If Not (converted_hr_expiry_timestamp = converted_ad_expiry_timestamp) Then ..., the first item in the comparison is a string; if you want to do this comparison, you need to either use ToString on the ad_expiry or parse the hr_expiry into a Date.
I would also recommend using Option Strict if you can to turn these implicit conversions into errors, or if that would introduce to many issues, at least turn on the warning for implicit conversions.
I know this is just working around the problem, and will stop it working locally for you (or rather move the problem to your machine), but if it's only ever going to be run on that server can you not just swap X and Y values?
Dim converted_hr_accountexpiry_timestamp= hr_row(0).Item("Termination Date") & ""
Dim hr_termdate_var() As String = converted_hr_accountexpiry_timestamp.split("/")
updatescript = updatescript.Replace("$x", "'" & hr_termdate_var(1) & "'") _
.Replace("$y", "'" & hr_termdate_var(0) & "'") _
.Replace("$z", "'" & hr_termdate_var(2) & "'")
Alternatively, if you want it to work on both systems then maybe a check before running the offending code is in order, something like this has worked for me in the past:
Try
Dim TempTimeString As String = "31/01/2020 01:00 AM"
Dim ConvertedTime As Date
ConvertedTime = DateTime.Parse(TempTimeString)
'''Don't swap X and Y as it was able to convert
Catch ex As Exception
'''swap X and Y as it was unable to convert
End Try
I'm working on a program that will add records to an access database once a VB form has been completed. Once stored the information can be searched and printed as needed. I'm having no issues with that.
The problem I'm having is when a Windows 7 computer submits information it changes the format of my DateTimePicker.
Ex. The Data was added using the date Wednesday, April 4, 2018. But on windows 7 if a user were to use the same exact criteria from the DateTimePicker and search by it the field would populate as Wednesday, April 04, 2018. Windows 7 adds a 0 placeholder to the front of what day it is when using the DateTimePicker. Is there a way to set the DateTimePicker in Visual Studio to override how Windows 7 is changing this value?
This is the line where my search adapter pulls information based on the DateTimePicker:
da = New OleDbDataAdapter("SELECT * FROM " + ComboBox1.Text + " WHERE Date like '%" & CodeText.Text & "%'", myConnection)
Thanks in advance.
Correction, I got it working. I don't know why I didn't think of it but I just set the DateTimePicker to a custom format and now it works between Win 10 and Win 7. Thanks!
Also it queries just fine, Steve.
I have an API that I want to update dynamically so that the user can enter a start date and an end date on a spreadsheet and my macro will pull back data for that particular date range.
The issue I'm having is that within the API URL the StartDate and EndDate parameters must be in the format yyyy-mm-dd as a string.
I've tried URL = "https:// ...&StartDate = Format(Date(),"yyyy-mm-dd") & EndDate=Format(Date(),"yyyy-mm-dd")&..." (the ... is for the things before and after the URL).
An example of the type of URL I'm looking at is:
https://www.googleapis.com/analytics/v3/data/ga?ids=ga:12345&startdate=2008-10-01&end-date=2008-10-31&metrics=ga:sessions,ga:bounces
I've also played around with adding in extra quotes within the URL string but I can't seem to get it to work.
I keep getting told that the dates aren't being recognised and therefore I can only get the code to run if I hardcode dates.
Any suggestions?
I noticed a few issues in the code posted. The & is the concatenation operator in VBA. You need to enclose that in "" to make sure you are returning the ampersand as a string, and not joining strings together.
I've added some sample code which hopefully illustrates the idea and get's you back up and running. The code should print out True if the createdURL and testURL are equal, or False if not.
Code
Option Explicit
Public Sub FormatExample()
'This is the example provided
Dim testURL As String
testURL = "https://www.googleapis.com/analytics/v3/data/ga?ids=ga:12345&" & _
"startdate=2008-10-01&end-date=2008-10-31&metrics=ga:sessions,ga:bounces"
'This is a built string example
Dim createdURL As String
createdURL = "https://www.googleapis.com/analytics/v3/data/ga?ids=ga:12345" & _
"&startdate=" & Format(#10/1/2008#, "yyyy-mm-dd") & _
"&end-date=" & Format(#10/31/2008#, "yyyy-mm-dd") & _
"&metrics=ga:sessions,ga:bounces"
'Print out if they are equal
Debug.Print createdURL = testURL
End Sub
I need some ideas on how I can accomplish what I'm attempting to do, here is the scenario.
I have 2 DateTimePickers (DateTimePicker1 and DateTimePicker2) to act as a date range. I need a function to :
1.) Download a file from my ftp with the initial date/time in yyyyMMdd.txt format
2.) Add 1 to the date and do the download again until DateTimePicker1 = DateTimePicker2
3.) If the file doesn't exist (its possible it may not), just move on to the next date.
I managed to create an infinite loop! It just won't repeat. I'm not familiar with Do While loops so any tips are weclomed!
I tried something like:
While DateTimePicker1 < DateTimePicker2
Do My.Computer.Network.FileDownload("ftp://address/", "ftp://address/" & folder & "/" & DateTimePicker1 & ".txt")
DateTimePicker1.Value.AddDays(1)
Loop
I think you need to compare the Value properties of the DateTimePickers and when you call AddDays() you have to assign the result back to the Value property like this:
DateTimePicker1.Value = DateTimePicker1.Value.AddDays(1)
The Value property is a DateTime object and AddDays() returns the DateTime object as a result.
So try this...
While DateTimePicker1.Value < DateTimePicker2.Value
My.Computer.Network.FileDownload("ftp://address/", "ftp://address/" & folder & "/" & DateTimePicker1 & ".txt")
DateTimePicker1.Value = DateTimePicker1.Value.AddDays(1)
End While
Here's a Fiddle Demo with just DateTime objects.
What i am trying to do is when i click a button i created i have data imported into a table. This works great right now. What i am wondering if there is a way that when i click this button if i can have a parameter box come up asking for the date that this data is from. once the user types that date in the date will be placed into a column(field) named timestamp.
Does this make sense? I have looked up on how to do this but i just found how to use parameters on querys.
I could really use the help. Thank you for the help in advanced.
You could do something like the following:
'... your existing code
dim dtTimeStamp
dtTimeStamp = InputBox("Please enter a date:")
'may want to validate date
If not isdate(dtTimeStamp) then
msgbox "Bad date"
end if
doCmd.RunSQL "Update TableX Set TimeStamp = #" & Format(dtTimeStamp, "yyyy-mm-dd") & "# where TimeStamp is Null"