Date Format Problem - asp.net

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.

Related

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.

How to insert or update data in datetime datafield in mssql2005

I have a textbox which displays the date as 01-May-2011 but the database coumis in format of datetime ... how to enter date in date time column of database. ..
how to wite the sqlquery for this ?
You can convert that format to a DateTime like this
string dateString = "01-May-2011";
string format = "dd-MMM-yyyy";
var result = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
if you're using LINQ to SQL or even ADO with a parameter of type DateTime, the conversion to a format that SQL understands will be done automatically for you.
If you're building the SQL by concatenating a string manually (not recommended!) you should try to reconvert to a string in the format 'yyyyMMdddd' (corrected as per AdaTheDev's comment, notice the single quotes). Other formats may or may not be recognized by sql depending on the language settings on both your client and your SQL Server
SQL Server is pretty good about taking in datetime values. If you pass the date as a parameter you can put quotes around it ('01-May-2011') and ignore the time. The database will automatically fill in a default time so that you don't have to worry about it.
Pass field value as nvarchar to database and use following to cast it to datetime.
Declare #dt nvarchar(20)
SET #dt = '01-May-2011'
select cast(#dt as datetime)
One thing to be aware of is that dates w/o time will be interpreted as May 1 2011 12AM. IE, without a time specified, SQL Server will always set the time to midnight. So if you have just the date as a field and you want records from May 1, you can't do
WHERE datefield = '5/1/2011'
This will find records where the datefield is May 1st Midnight. You have to do
WHERE datefield >= '5/1/2011' and datefield < '5/2/2011'
This doesn't really pertain to your question, but I've seen it trip up a LOT of people. Myself included.
Just convert it to dateTime
DateTime _ConvertedDate = Convert.ToDateTime(txtDate.Text);
this converts into datetime

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

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.

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.

Resources