stop vb.net from turning 02/02/2011 to 2/2/2011 - asp.net

For some reason vb keeps changing my dates format and removes the 0s at first this wasnt a problem but it really messes up my sorting in my gridview.
Dim aftersubtraction As Date
aftersubtraction = departuredate.AddDays(-dates1.Text)
dates.Add(aftersubtraction.AddDays(-gracep.Text))

DateTime objects store their variables as integers. It will always engage in this behavior. To prevent it, you need to format the date as a string of your choosing before you send it where-ever you send it:
aftersubtraction.ToString("MM/dd/yyyy")

Don't confuse how a date is stored internally (doesn't really matter), to how you display it.
"Feb 2nd 2011" is the same date as "02/02/2011" or "2/2/11".
When you have a date variable and want to display it a certain way, you should use the correct format string - either a custom or a standard one.
In your case you seem to want this:
Dim outputDate as String = myDate.ToString("dd/MM/yyyy") ' European/UK style
Dim outputDate as String = myDate.ToString("MM/dd/yyyy") ' US style

Try this:
.ToString("MM/dd/yyyy")

In addition to what Joel said - you shouldn't be sorting on the string representation of a date object - you should be sorting on the date value itself, then it won't matter how it's sorted.

Change your Region and Language settings to your correct culture this will probably solve your issue, but if you have problems with sorting dates in a gridview you might be passing a datasource that stores the date as a string.

Related

Strange issue with Date.Parse / ParseExact not altering date (ASP.Net)

I have a bit of a head scratcher with the Date.Parse /ParseExact functionality in VB.
To surmise, I have an ASP.Net 4.0 app, on one of the pages there is a calendar control which the user chooses a date and time, these are fed into a string (strReqDeadline) which takes the following European / UK date time format: dd/MM/yyyy HH:mm:ss.fff
So for example the contents of strReqDeadline would be: 29/03/2013 16:30:00.000
I then need to insert this into a SQL datetime column, so obviously it needs converted from UK to the US/datetime format. I've been attempting to do this with Date.Parse and Date.ParseExact with no success. The following should work according to the research I've done:
strReqDeadline = "29/03/2013 16:30:00.000"
Dim usDate = As Date = Date.ParseExact(strReqDeadline, "dd/MM/yyyy HH:mm:ss.fff", System.Globalization.CultureInfo.InvariantCulture)
However, what actually happens at runtime is bizzare, the Date.ParseExact function trims off the fractal seconds from the time (as far as I can see it shouldn't be doing this because the filter specifies .fff), and otherwise leaves the entire string completely unchanged.
So, if the value of usDate is output, it appears as follows: 29/03/2013 16:30:00
What it should contain is datetime: 3/29/2013 4:30PM
The really strange thing is if I put a watch on usDate and start the app, in the development environment its value shows as #3/29/2013 4:30PM#, both in the watch list and when hovered over in the source window, but any form of output displays the original string, just minus the fractions of second, and doesn't convert to datetime.
From what I read the 'InvariantCulture' specification should negate any locale specific issues with output, but just in case this were the issue I also tried specifying an explicit local culture with System.Globalization.CultureInfo.CreateSpecificCulture("en-GB") (tried fr-FR too), but this makes no difference. The Windows regional settings on both the client and server are set to UK if this bears any relevance.
Maybe I'm missing something very obvious but I just can't see why I'm getting this output, Date.ParseExact doesn't throw any exceptions or complain about the string not being recognised, but I'm struggling to understand why it just removes the fraction seconds and does nothing else, especially since the input spring matches the specified mask exactly.
I'd be very interested to hear if anyone else has experienced an odd issue like this and what you did with it!
Thanks :)
EDIT: Full code with SQL section is as follows:
strReqDeadline = "29/03/2013 16:30:00.000"
Dim usDate As Date = Date.ParseExact(strReqDeadline, "dd/MM/yyyy HH:mm:ss.fff", System.Globalization.CultureInfo.InvariantCulture)
'SQL
Dim con As New Data.SqlClient.SqlConnection("data source=XXXXX;initial catalog=YYYYY;Integrated Security=True")
Dim cmd As New Data.SqlClient.SqlCommand()
cmd.Connection = con
cmd.CommandText = "INSERT INTO Requests (ReqOwnerID, ReqDeadline, ReqStatus)" _
& "VALUES ('" & UserID & "', '" & usDate & "', '1')"
con.Open()
Dim NewReqID = cmd.ExecuteScalar()
con.Close()
'
Why is it you thin it is not working? These are all the same underlying date/time:
29/03/2013 16:30:00.000
29/03/2013 16:30:00
3/29/2013 4:00PM
You cannot rely on what hovering over a non-string variable shows to determine its inner value. All you are seeing is the evaluation of ToString(). If you want a String to show the fractions seconds, then you need to call ToString() and specify the format "dd/MM/yyyy HH:mm:ss.fff". By default a DateTime type if not going to show your fractions seconds when you convert to a String.
If you are not using parameters (and you should be) then your final SQL statement after injecting the DateTime would be something like this:
INSERT INTO MyTableWithDate
(column1
,column2
,MyDateCol)
VALUES
('a'
,'b'
,'20130329 16:30:00.557')
As I mentioned before, a Date datatype is not String. It's an object (or a rather a DateTime structure, by I digress). You must call the correct ToString() meth0d.
Try using this withing your SQL string:
& "VALUES ('" & UserID & "', '" & usDate.ToString("yyyyMMdd HH:mm:ss.fff") & "', '1')"
Of course, there is little point converting a string to Date object to immediately convert it back to a string again, but this code should work.
usDate is an object of type DateTime, and it appears to be storing the correct value. When you are inspecting it, you are seeing a string representation of that datetime value. It doesn't contain either 29/03/2013 16:30:00 or 3/29/2013 4:30PM, those are just two valid representations of what it contains.
You say
any form of output displays the original string
This is not true. In fact you have control over how it is output when you call ToString(), where a format can be specified
What you are doing looks correct i.e. using Date.ParseExact to convert a date in UK format to a Date type. The issue you are having is that when it displays this as a string it is displaying it in your local culture (the debugger appears to always want to display in US format), but the Date you have set is correct.

How to know which in *format* is a date returned, in ASP.NET

The following code, d has the current date. Depending on the current locale, it will return a date.
Dim d As Date = Date.Today
Note: I don't want to check whether the date is valid or not, but rather to know, whether it is in a 'dd-MM-yyyy', 'MM-dd-yyyy' or any other date format..
EDIT (29/06/2012 - Friday):
The reason I am asking this question is because I am sick of trying to deal with dates in ASP.NET. I build a project on my local PC, where dates are "dd/MM/yyyy" and as soon as I upload it to the production server (usually in US, hence MM/dd/yyyy) the code breaks.
So I usually deal with dates by converting them into yyyyMMdd format and also keep them in the database like that. That is the closest I get to an exception-free coding.
In this case, it makes sense that there is no way to get the format from a returned date string. Therefore, I will carry on with my approach.
Date.Today is a DateTime, not a string. Thus, it does not have an inherent format.
It will return a Date, which I believe is a VB alias for DateTime. (If it's not, just use DateTime explicitly to be idiomatically .NET rather than using the legacy VB types.)
A DateTime value itself doesn't have a format, any more than an int is in decimal or hex. It's only when you convert the value to a string that a format is applied, and then it depends on how you convert it to a string. You shouldn't use a string conversion until you really need to, and then you should control the format so that it works the way you want it to.
As far as possible, convert text data into its "natural" type as early as possible, and keep it in that type for as long as possible. For example, avoid converting to strings when passing values in SQL queries - instead, use parameterized SQL where you can specify the parameter value as a DateTime.
What you want to know is found in:
CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern
This is the format string that will be used when you call
d.ToShortDateString()
You need to be TOLD; there's no other way. Take for example:
6/12/2012
It's valid in dd/mm/yyyy or mm/dd/yyyy format
Which one do you pick if you don't know the locale/format beforehand?
Date values don't have an intrinsic format. In other words, you can format the date to any string representation you need but the opposite conversion from a string back to a Date value requires that you know in which format you are receiving this date string.

Date and DateTime problem

I am developing an application using ASP.NET (C#) and SQLServer 2008. In my database i have a field DepositDate and datatype is "DATE". On my data entry form i am taking dates using jquery datepicker and its returning date in textbox as dd/mm/yyyy format as per user requirement whereas i noticed in database its keeping date values as yyyy-mm-dd..i am confused.
While saving record i am getting not a valid date time as the only available conversion format is Convert.ToDateTime and my data requirement is DATE only.
Can anyone suggest solution how to deal with it.?
here is the code
DateTime thedate = DateTime.Parse(txt_IDate.Text);
DateTime mdate = DateTime.Parse(txt_Mdate.Text);
db.AddInParameter(cmd, "#SIssueDate", System.Data.DbType.Date);
db.SetParameterValue(cmd, "#SIssueDate", thedate.ToShortDateString());
db.AddInParameter(cmd, "#SMaturityDate", System.Data.DbType.DateTime);
db.SetParameterValue(cmd, "#SMaturityDate", mdate.ToShortDateString());
Why are you setting the parameter values to strings in the first place? Just use the DateTime values themselves:
db.AddInParameter(cmd, "#SIssueDate", DbType.Date);
db.SetParameterValue(cmd, "#SIssueDate", thedate);
db.AddInParameter(cmd, "#SMaturityDate", DbType.DateTime);
db.SetParameterValue(cmd, "#SMaturityDate", mdate);
I doubt that your database is storing the values in any particular string format... they're not strings, they're dates. It's like asking whether a database stores an integer in a hex or decimal format... it just stores the number.
Basically, you need to parse the user's input data in the appropriate format coming in (which presumably you're already doing) and then format it again when you fetch it. Aside from the presentation layer, you should only ever think of it as a date value, without any associated format.
It may be helpful to imagine two users from different countries, who each view a list of dates. The would each want to see those dates in a format appropriate for their culture - so they may see different representations, but they'd be seeing the same actual dates.
If that suits You, You can do it like thedate.ToString("yyyy-MM-dd") and You will get only 2011-01-20

Convert.ToDatetime not adding timestamp

For example:
Dim testdate As String = "29/10/2010"
testdate = Convert.ToDateTime(testdate.ToString)
Response.Write(testdate)
expecting "29/10/2010 00:00:00" what I get is "29/10/2010"
You have to assign the result of Convert.ToDateTime to a DateTime object, not to the string.
Dim testdate As String = "29/10/2010"
Dim date As DateTime = Convert.ToDateTime(testdate)
Response.Write(date)
This will print the clock as well as the date in the default format for your machine.
The big problem is, as mentioned in other posts, you are implicitly assigning the DateTime result of the Convert operation to a string variable. This wouldn't even pass the compilier in C#, so your into the realm of how VB operates on these implicit assignments and you probably don't want to be there because if some part of the language specification changes in a new Framework version and you try to migrate your code, you could potentially have a nasty bug to try to find (maybe not as important here, but in other cases, yes). Best move would be to rewrite the code block to have the Convert operation assign to a DateTime object, but simplier solution would be to throw a .ToString() at the end of the Convert.ToDateTime(testdate) line (i.e. testdate = Convert.DateTime(testdate).ToString() which will leave testdate with the date and the timestamp formatted to the current culture (as you are now performing an explicit conversion between the DateTime and the destination String).
As clearly documented here, no, this is not the designed behaviour.
'05/01/1996' converts to 5/1/1996 12:00:00 AM.
'Tue Apr 28, 2009' converts to 4/28/2009 12:00:00 AM.
It's possible that this article might provide insight.

Date Format Problem

i cant change date value to the format which i want.This is my code.When i execute this code,i see mydate as mm/DD/yyyy format.what do i miss?
Dim dateString As String = Date.Now.ToString("dd.MM.yyyy")
Dim myDate As Date = Date.ParseExact(dateString, "dd.MM.yyyy", Nothing)
You don't miss anything. myDate is a Date which internally stores the date as a numerical form (as an UInt64 to be more precise). It does not store the string representation of the date, and it has no format in itself. When it is displayed as a string (for instance using the ToString method), if no date format is specified, it will use the default format for the current culture, which in your case seems to be MM/dd/yyyy.
Update
I will try to make this a bit more clear.
What you are experiencing is actually a rather common misunderstanding. You really need to make a difference between a date and the string representation of a date. These are two different things.
The Date (which is acutally a DateTime with no time information, so I will refer to DateTime here) stores the date and time internally as a number. Currently, where I am, this number is 9857259848526375120. That is the current date and time, as represented inside a DateTime object.
While this value is very useful to the code, it makes little sense for us humans. We have complicated the matter a bit more by deciding to write dates in different ways in different countries. So, here in Sweden, todays date would be written as "2009-09-17", while in Turkey it would be "17.09.2009".
So, in order to make things easier for us, whenever a DateTime object is displayed as text (in the VS debugger, when printed on screen and so on), the numerical value is formatted into a string using some date format. This format will be different in different countries. If no format is specified when displaying the string, the default format for the current culture will be used. This is the case in the VS watch window for instance.
If you wish to get the string representation of the DateTime object formatted according to a specific culture, you can pass it to the ToString method as such:
myDate.ToString(CultureInfo.GetCultureInfo("tr-TR"))
If you, on the other hand, need to convert the date into some other, specific format, you can use a format string to achieve that:
Dim formattedDate1 As String = myDate.ToString("dd'/'MM'/'yyyy")
Dim formattedDate2 As String = myDate.ToString("dd.MM.yyyy")
Note the single quotes around the / characters in the format string; they are needed since the system will by default interpret the / as a placeholder for the current culture's date separator. If you wish to force the formatted date to use a / character rather than the normal separator for the current culture ('-' in Sweden, '.' in Turkey), you need to escape it as in my example.

Resources