datetime to DateTimePicker VB.Net in Long format and vice versa - mysql

Is it even possible to save the value of DateTimePicker (Long format) to datetime (database). Then do the reverse from datetime (datebase) set to DateTimePicker. Do we have a simpler code for this?
I am using MySQL in VB.Net Windows Form.
here's my code in vb.net:
'" & date1.Value.ToString("yyyy-MM-dd") & " " & date1_time.Value.ToString("hh:mm:ss") & "." & Now.Millisecond & "'
in MySQL:
date1 datetime

Assuming that you are talking about a Windows Forms DateTimePicker, there's nothing do. The Format and CustomFormat properties of the control only determine how the data is displayed. The Value property is still type DateTime and that has no format. It's just a number. When you save to the database, you save that DateTime value and it gets - or at least, it should get - stored in the database in its native date/time data type too, so format is again a non-issue. In MySQL, you should generally be using the DATE data type for dates without a time portion or DATETIME for values with both date and time. At no point should you ever convert the values to text yourself in this whole process. That part is handled by the DateTimePicker control.
If you're using an appropriate data type in the database as it sounds like you are, then you will be getting a DateTime from the database. You just assign that directly to the value property, e.g.
myDateTimePicker.Value = CDate(myDataRow("MyColumn"))
or:
myDateTimePicker.Value = myDataReader.GetDateTime(myDataReader.GetOrdinal("MyColumn"))
To save the data back to the database, you simply create a parameter on your command in the same way as you would for any other data, then assign the DateTime to the Value of that parameter, e.g.
myCommand.Parameters.Add("#MyColumn", MySqlDbType.DateTime).Value = myDateTimePicker.Value
If you don't know how parameters work, look that up now as it is the ONLY acceptable way to insert variables into SQL code.

Related

MS Access Date/Time format issue?

This might be a possible duplicate, but I have a strange issue with MS Access DB.
When I update a Date/Time value for my column req_date, I'm facing a problem.
10-03-2017
is getting updated as below
10-03-2017
where as
10-18-2017
is getting updated as below
18-10-2017
I'm using the following code in c# to Execute the query:
query = "update gb_jobs set req_delivery=myDate"
myCMD = new OleDbCommand(query, con, trans);
int tempCnt = myCMD.ExecuteNonQuery();
where as myDate is already converted to string from date time,
As per the solution by Albert, I concatenated my myDate to #myDate# but it is throwing following error:
query = "update gb_jobs set req_delivery=#myDate#"
Error : Data type mismatch in criteria expression.
You don’t mention where/when/how you are updating that column in question.
As a general rule, if the VBA variable type is an actual DATE type variable then you can assign such values directly to a control or recordset in code.
However if ANY of your code uses a string result, then you MUST format the string as USA format regardless of your computer's regional settings. Your regional settings will thus transform the date display to whatever floats your boat.
So any of your date formats have to be of mm/dd/yyyy. Given your examples, it looks like you are following that format. This suggests that you have your DISPLAY set to DD/MM/yyyy. So in theory what you have given so far is correct behaviour.
What this suggests is that your result of 10-03-2017 ACTUALLY means 03/10/2017. So it is in fact March and not October.
Thus in VBA code to update (or query) some data, you have to go:
dtStart as date
dtEnd as date
If you set the value of above two dates, then to query the data, you MUST go:
strWhere = "InvoiceDate >= #" & format(dtStart,'mm/dd/yyyy') & "#" & _
" and InvoiceDate <= #" & format(dtEnd,"mm/dd/yyyy") & "#"
Docmd.OpenReport "rptInvoice",acViewPreview,,strWhere
So any code that will query, or update values with SQL has to re-format the data to USA format (mm/dd/yyyy). What the control and forms will display is as noted whatever you have in windows regional panel, but ALL internal code must format strings as mm/dd/yyyy.
So it not clear how you are making the change, but from what you have given so far, your DISPLAY of info is dd/mm/yyyy, but you are entering the data as mm/dd/yyyy which is correct. If you are entering this data on a form and not using code, then from what you have given your date format as set by windows is dd/mm/yyyy.

MS Access convert short time in form to decimal time in table

I have an Access database with a form that contains a "ProcessTime" field, with the format hh:nn and the input mask 00:00. I've got that part working fine. In the Control Source on the associated table, however, I would like the ProcessTime field/column to appear as decimal minutes. I haven't been able to figure out how to do that.
For example, a user might enter a ProcessTime in the form as 01:30, meaning 1 hour and 30 minutes. I would like the associated value in the table to then appear as 1.5, meaning 1 and a half hours.
How can I go about modifying the ProcessTime field in the table to show the time in decimal hours? I had assumed there would be some simple "decimal time" format I could enter for the ProcessTime field in Design View, but I haven't found one yet.
I'm using MS Access 2013.
There is no intrinsic format or conversion function for this. Don't modify the field. Do a calculation in query or textbox.
[ProcessTime] is a date/time type? The following expression will work for date/time or text type.
Hour([ProcessTime]) + Minute([ProcessTime])/60
If the textbox is bound to the field, it will be problematic to make a conversion like that as you will have different data types (date/time and decimal). If it is not a bound textbox you can split the textbox value on the colon (:) and then concatenate hours & (minutes/60) and then write the information to the table.
Dim temp as string
temp = split(ProcessTime.Value,":")
currentDB.Execute "Update <table name> SET ProcessTime=" & temp(0) & temp(1)/60 & "WHERE <condition>;"
'Or you are adding a new record you can do an Insert Query
' Replace the Update statement above with "INSERT INTO <table name> (<other fields>,ProcessTime) VALUES (<other values>," & temp(0) & temp(1)/60 & ");"

How to check if a string contains a date?

I'm trying to iterate on a DataSet, this contain a results of query such as SELECT * FROM tb 1, now the first three field contains a date, the format saved in the database table is this:
yyyy-MM-dd HH:mm:ss
but the code return this:
yyyy/MM/dd HH:mm:ss
in particular this:
For z = 1 To ds.Tables(0).Columns.Count - 1
Console.WriteLine(ds.Tables(0).Rows(x)(z).ToString())
Next
So I need to recognize if the current string have this format: yyyy/MM/dd HH:mm:ss and parse it into: yyyy-MM-dd HH:mm:ss I tough to a regex pattern for recognize it, but I'm not an expert of regex. Anyway, if there is another solution I'll glad to see. Note that only the first three value and the last one of the table is date, the other values aren't date but contain integer or other string value.
Dates do not have a format. From MSDN:
Represents an instant in time, typically expressed as a date and time of day.
...
Time values are measured in 100-nanosecond units called ticks, and a particular date is the number of ticks since 12:00 midnight, January 1, 0001 A.D. (C.E.) in the GregorianCalendar calendar...For example, a ticks value of 31241376000000000L represents the date, Friday, January 01, 0100 12:00:00 midnight.
So, a DateTime is just a Big Number. Representing them as "dd/MM/yyyy" is part of the magic of the DateTime type. Part of the issue is this:
Console.WriteLine(ds.Tables(0).Rows(x)(z).ToString())
Row items are Object. It wont act like a DateTime type unless/until you get it into a DateTime variable. That print as a DateTime simple because the DataTable knows the underlying type; but it will use the default format for your Culture. This makes it look like dates have a built in format (or even that the "format changed" if you tried to set it to something), but you are a human and 635882810022222112L would not make sense to most of us.
To change the output style, you first need to get it into a DateTime variable. Apparently, a preliminary step is to determine if an arbitrary column is a Date. Rather than testing the "format" of the output, test the underlying data type. This does assume a proper DateTime column in the DataTable:
If ds.Tables(0).Columns(n).DataType = GetType(DateTime) Then
'...
End If
' Or:
If ds.Tables(0).Rows(x)(z).GetType Is GetType(DateTime) Then
'...
End If
Then to change the display, first get it into a DateTime variable:
Dim dt As DateTime
If ds.Tables(0).Rows(x)(z).GetType Is GetType(DateTime) Then
dt = Convert.ToDateTime(ds.Tables(0).Rows(x)(z))
' cant change "format" but you can change how it displays:
Console.WriteLine(dt.ToLongDateString)
Console.WriteLine(dt.ToString("yyyy-MM-dd HH:mm tt"))
Console.WriteLine(dt.ToString("dd MMM, yyyy"))
End If
An easier way to get and convert to DateTime is to use the Field(Of T) extension:
Dim dt = ds.Tables(0).Rows(x).Field(Of DateTime)(y)
when I peform the insert usually do this: Date.Now.ToString("yyyy-MM-dd HH:mm:ss") so I apply a format to date to insert... if I don't format correctly the date as I shown I get this value 0000-00-00 00:00:00
That doesn't apply a format to a date. It converts the DateTime to a string. While "yyyy-MM-dd HH:mm:ss" is the correct format to use when passing date data as a string to MySql, it is not needed. The MySQL Data provider knows how to convert a Net DateTime var to the data MySql needs/wants and back again -- that's its job.
' this will work fine
cmd.Parameters.Add("#SomeDate", MySqlDbType.DateTime).Value = myDateTimeVar
The format requirement you read about is the what you need to use in the MySql shell or WorkBench UI because you are entering text/string there...from the keyboard. It does not mean code must convert DateTime variables to string in a specific format for storing.
I ended up using this
Try
Dim theDate As DateTime = dr.Item(colName)
Return theDate
Catch
' do something
End Try
I would be happy to see a better method.
Based off of what you seem to be asking a simple replace would do
For z = 1 To ds.Tables(0).Columns.Count - 1
Console.WriteLine(ds.Tables(0).Rows(x)(z).ToString().Replace("/","-"))
Next
if it comes in with / they are changed to - if it comes in with - they remain intact.
Depending on the flexibility you want in this, it may be necessary to TryParse to ensure that the value you're working with is actually a valid datetime.

How to separate time from datetimepicker vb.net

I have one datetimepicker which custom format MM/dd/yyyy h:mm tt
I have database and has a column "Date_Time" the value of the DateTimePicker is saved to the column Date_Time formatted like this MM/dd/yyyy h:mm tt
now i want to get the Time only not the entire value of datetimepicker just the hh:mm tt from the column Date_Time
SORRY FOR MY GRAMMAR
How about DateTime.TimeOfDay?
It returns the time that has elapsed since midnight (which is what h:mm tt stands for in your code).
Dim Time As TimeSpan = DateTimePicker1.Value.TimeOfDay 'Would return for example 3:14 PM
The answer above is right.
If you need to get time string, you can use also another way, which includes a formating:
Dim myTimeString = DateTimePicker1.value.ToString("hh:mm")
You can do that for any part of the DateTime value.
You are heading for a new problem. If you zero out the Date portion and store the result to a DateTime column, you will end up storing something like: 0001-01-01 16:43:12. A column defined as DateTime will always have a Date, as will a DateTime variable.
The first problem may be getting MySQL to accept a non-Date in a DateTime column. Using a column defined as DateTime(3), mine throws a generic fatal error exception trying to store just a TimeSpan to it:
cmd.Parameters.Add("#p3", MySqlDbType.DateTime).Value = DateTime.Now.TimeOfDay
cmd.ExecuteNonQuery()
If MySqlDbType.Time is used as the type, I get an exception that the time is an invalid value for the column...and it is.
If you manage to store it somehow, the next problem will be when/if you want to put that value back in a DateTimePicker: the minimum date you can enter is 1/1/1753 (first full year of the current calendar). So your DateTime var with the Date zeroed out wont work. You'll first have to restore the date portion, but the Date, Year etc are all readonly.
Solution 1
Define the column as Time(0) which will store hours, minutes and seconds. Use the value in the parens to specify fractional seconds, for instance Time(3) will also store milliseconds. When you read the data, store it to a TimeSpan.
Then in your UI use a different control, otherwise you have the same problem - adding some Date data to it to make it usable in a DateTimePicker
Solution 2
Use a DateTimePicker and a DateTime column, but just ignore the Date portion in your code. This will allow you to use what is in the Database as is with the control.
You can get the time selected with DateTime.TimeOfDay but storing and reusing it may be problematic.

Converting user-typed dates from date picker

I have a report that uses date params (so have to be datetime in SSRS, which sucks to start with). When the user enters a date such as "5/1" it creates a DateTimeOffset data type and I can't find anyway to cast it to anything else, format it, or concatenate in a text box. I tried casting to a date to a string, etc. All I get is:
Conversion from type 'DateTimeOffset' to type 'String' is not valid. ('String' is replaced by anything I try to cast it to)
Surely there must be a way to have a text box show "From 5/1/2013 to 5/31/2013" when the user types "5/1" and "5/31" in the date field? Does Microsoft really think computer-literate people want to pick up the mouse to use their date picker instead of using tab?
Try the following expression:
="From " & Format(Parameters!Param1.Value.DateTime, "M/d/yyyy") & " to ..... etc"
To test this expression I've created a fresh report, added a DateTime parameter, and entered "5/1" in the textbox, hit enter. The report comes up with the following textbox:
From 1/5/2013 to ..... etc
For my locale, this is correct, because when entering DateTime values days are assumed to come before months. When the report is viewed the textbox will also update and show:
5-1-2013 0:00:00 +01:00
From this you should be able to extrapolate and use it for a second parameter as well, extending the expression to show the exact string you need in your report.
The Parameters!Param1.Value.DateTime helped when the user omits the year, but it broke down when the user decides to include the year. I couldn't get it to work under both conditions.
Try this.
Include the date parameter value as a field in your resultset. Your SQL might look like:
SELECT field1, field2, Convert(date, #FromDate) [FromDate_param] FROM table
Then you can create an expression in SSRS like:
="From " & Format(First(Fields!FromDate_param.Value), "M/d/yy")