How to check if a string contains a date? - mysql

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.

Related

Conditional formatting for current day date

I am just trying to getting my data to do a color fill if the date value equals today.
The data is coming from oracle:
=IIf(Fields!finishDATE.Value = Today(),"Yellow","Transparent")
This will not give me any errors nor will it do the function according to the expression. None of the data with the finish date equaling today highlights.
If today is 8/24/2021 it should look like this:
3/22/2021, 8/24/2021, 2/22/2021
As I'm not sure what format the data will come in from Oracle (I'm a MS SQL person) then this might be overkill but try this
=IIF (Format(Fields!finishDATE.Value, "yyyyMMdd") = Format(Today(), "yyyyMMdd"), "Yellow", Nothing)
All I'm doing here is comparing just the date parts of the date/datetime values.
Below is the output. The first column is the actual date column contents including a time, then for illustration only, the 2nd column shows it formatted to just the date part and the 3rd column show today() with the same format applied.
Finally, I used the keyword Nothing (SSRS almost equivalent of NULL) as this is the correct default value.

Need date in "dd-mm-yyyy" format in JSON

I need to give date in "dd-mm-yyyy" format in REST API. But the API response always comes in "yyyy-mm-dd" format even if i changed the format of date field to "99-99-9999". It seems it always gives date in ISO 8601 format no matter what format i choose.
I checked session:date-format and it's already dmy. "write-json()" method also has the same problem. But i only need it in REST webservice. Progress verison: 11.3.
Please see this for more clarification:
DEFINE TEMP-TABLE ttdate
FIELD fdate AS DATE FORMAT "99-99-9999".
CREATE ttdate.
ASSIGN ttdate.fdate = TODAY.
CREATE ttdate.
ASSIGN ttdate.fdate = TODAY - 15.
TEMP-TABLE ttdate:WRITE-JSON("file", "D:/ttdate.json", YES).
{"ttdate": [
{
"fdate": "2019-02-19"
},
{
"fdate": "2019-02-04"
}
]}
In JSON, it always gives in YYYY-MM-DD no matter what format i choose. Please don't suggest to use string it will be a huge pain for me to use string.Please note that I am concerned about date format in JSONs only.
You can always keep it simple/force it as a character instead of a date:
DEFINE VARIABLE dt AS DATE NO-UNDO.
DEFINE VARIABLE c AS CHARACTER NO-UNDO FORMAT "x(12)".
dt = TODAY.
c = STRING(DAY(dt),"99") + "-" + STRING(MONTH(dt),"99") + "-" + STRING(YEAR(dt), "9999").
DISPLAY c .
31-01-2019
However, this really works for me, for this use case (displaying).
SESSION:DATE-FORMAT = "dmy".
DISP TODAY FORMAT "99-99-9999".
#Jensd first solution sounds like what you will need in your case. When using the WRITE-JSON method, I don't think you have any control over the format of the data. In cases where the other end needs very specific formats for data, a string is sometimes the only way to get it.

Coldfusion datepicker dd/mm/yyyy but MySQL stay with format yyyy/mm/dd

Datepicker is an option for user easy to pick the date to fill the form. In coldfusion, there is a fill form that need to use datepicker and after user selected the date and fill the form with format yyyy/mm/dd by default format which is MySql can read. If i change into dd/mm/yyyy and click save into MySql will get error because from what i know default format for MySql is yyyy/mm/dd.
<input type="text" name="Date_joined" size="auto" style="border:0px"required="yes">
This is the function to popup datepicker :
<a href="javascript:showCal('Calendar1')">
This is logo for datepicker :
<img align="right" src="calendar_menu.gif" alt="Select a date" border="0"></a>
Is there any solution for user pick a date and input text will display dateformat dd/mm/yyyy but still can save into MySql without error.
How to make MySQL accept a user input in format DD/MM/YYYY so the data will be recorded
If you want to save a string of numbers and dashes that represents a date in the format you want it displayed on a screen, then just make your database column a CHAR(10) and be done with it.
But, if you want to do calculations against it, aggregate data by it, DO THINGS with it, then save it as a date type. Don't worry about how your database UI represents that date value to you. Maybe it's different from how you want it shown on an HTML page, it doesn't matter. What matters is that as a date object, you can easily use and display that value however you like.
From what I know, MySQL will only accept datatype date with format YYYY/MM/DD.
Not how that works.
https://dev.mysql.com/doc/refman/5.7/en/datetime.html
The DATE type is used for values with a date part but no time part.
MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. > The supported range is '1000-01-01' to '9999-12-31'.
See that "retrieves and displays" (emphasis mine)? It's just a date object with "00:00:00" as the time portion.
So however your form field accepts the string representation of the date, you need to convert it to a proper date object. Per Dan's suggestion, you can easily use parseDateTime() to accomplish this.
#writeOutput( parseDateTime( now() ) )# will output {ts '2018-03-14 15:29:19'}.
If your form field contains a valid string that represents a date (e.g. 2018-03-14):
#writeOutput( parseDateTime( form.myDateField ) )# will output {ts '2018-03-14 00:00:00'}.
So the value will be saved as a date object, without the time portion. When you read the saved value later, just use dateFormat() to display it in any format you like.
(Moved from comments for greater visibility)
One important addition to Adrian's answer. In this specific case, you MUST use a date mask with parseDateTime(). The mask controls how parseDateTime() interprets the input. Without the correct mask, the results may be wrong for your specific input, namely dd/mm/yyyy.
TryCF Example
Code:
<cfscript>
dateString = "05/08/2018";
writeOutput("<br>Without mask = "& parseDateTime( dateString) );
writeOutput("<br>With mask = "& parseDateTime( dateString, "dd/MM/yyyy") );
</cfscript>
Result:
Without mask = {ts '2018-05-08 00:00:00'} (May 8, 2018)
With mask = {ts '2018-08-05 00:00:00'} (August 5, 2018)

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.

How to subtract certain minuted from a DateTime in SPSS

I have timestamps in a column which I have imported in SPSS. Example, 7/6/2011 2:21 in a column called 'Observation'
This is in the string format. Now I also have timezone corrections for these data. So, -60 would mean subtract 60 minutes from this date.
How would I do this in SPSS syntax?
There are native date formats in SPSS, but unfortunately it does not appear that any cover the example you posted. I would parse the beginning of the string field to get the mm/dd/yyyy and the hh:mm part seperate, convert those into their representative time formats, and then do the time calculations.
For an example
data list fixed / observation (A25).
begin data
7/6/2011 2:21
10/11/2011 15:42
07/06/2011 02:21
3/15/2011 0:21
end data.
*getting the data part, assuming the space will always delimit the two parts.
compute #space = char.index(observation," ").
string date (A10).
compute date = char.substr(observation,1,#space-1).
*getting the time part.
string time (A5).
compute time = char.substr(observation,#space+1,5).
execute.
*now converting them into date formats.
alter type date (A10 = ADATE10).
alter type time (A5 = TIME5).
*you should check these carefully to make sure they were converted correctly.
*now making one time variable.
compute date_time = date + time.
formats date_time (DATETIME17).
execute.
*now it is just as simple as subtracting the specified value.
compute date_time_adj = DATESUM(date_time,-60,"minutes").
execute.
formats date_time_adj (DATETIME17).