Showing posts with label date. Show all posts
Showing posts with label date. Show all posts

Saturday, March 31, 2012

String to date

I have a string which contains a date in "MM/dd/yyyy" format. How to I convert that in VB to "dd/MM/yyyy"

Please see this post.

http://forums.asp.net/1167602/ShowPost.aspx


Thanks for that

String To Date

Hi, I have a vb.net/asp.net 1.1 web application that may be used in
other cultures where dates are formatted differently. I have three
controls (either DropDowns or TextBoxes) one for year, one for month,
and one for day.
I'd like to be able to convert this to a DateTime type of variable and
not have to rely on or find the localization settings.
My idea was to populate the DateTime.Year, DateTime.Month and
DateTime.Day from the controls, (like Date.Year = txtYear.Text) but
those properties are read-only.
I know I could make a string like "12-19-2005" and do a
strDate.ToDateTime but that will break as soon as the application is
used where dd-mm-yyyy is the norm.
So If I have three variables representing year, month, and day what's
the best way to convert to Date without relying on any kind of
localization setting? Thanks!
Mattit works in ASPNET 2.0,
it should work in ASP.NET1.x
Dim MyDate As New DateTime(2005, 12, 19)
Daniel TIZON
MCP - MCSD.NET - MCT
"MattB" <somedudeus@.yahoo.com> a crit dans le message de news:
40osodF1b4pklU1@.individual.net...
> Hi, I have a vb.net/asp.net 1.1 web application that may be used in other
> cultures where dates are formatted differently. I have three controls
> (either DropDowns or TextBoxes) one for year, one for month, and one for
> day.
> I'd like to be able to convert this to a DateTime type of variable and not
> have to rely on or find the localization settings.
> My idea was to populate the DateTime.Year, DateTime.Month and DateTime.Day
> from the controls, (like Date.Year = txtYear.Text) but those properties
> are read-only.
> I know I could make a string like "12-19-2005" and do a strDate.ToDateTime
> but that will break as soon as the application is used where dd-mm-yyyy is
> the norm.
> So If I have three variables representing year, month, and day what's the
> best way to convert to Date without relying on any kind of localization
> setting? Thanks!
> Matt
Daniel TIZON wrote:
> it works in ASPNET 2.0,
> it should work in ASP.NET1.x
> Dim MyDate As New DateTime(2005, 12, 19)
>
Perfect. Thanks!

String to date error

Hi guys Ive got a slight problem..

When i run my asp.net page through visual studio the application works fine, however when i puslish it and view it over myhttp://localhost page i get the following error "Conversion from string "28/8/2007" to type 'Date' is not valid." when selecting dates from a calendar control i created.

Im thinking this is some formatting issue having to do with EU/US Date format, however im not too sure about it and with a few research there are some help files stating to use globalization and once again im not sure how that works.

What im doing is assigning a date within an arraylist (which are of type dates) to a Date variable as below

Dim tempDate asDatetempDate = NewDate.Item(0) // arraylist of containing dates
Would appreciate some help regarding this issue

Thanks :)

It is a en-eu related problem. This article should help

http://msdn2.microsoft.com/en-us/library/2h3syy57.aspx
thanks that was interesting, also found out that the root to the problem was due to regional settings under the aspnet user account, my currently logged on account was set to UK however the user account aspnet was still on US therefore it kept showing dates in US format

String to Date conversion

Im trying to convert the input of several dropdownlists into a Date, but I can get an error and dont know how to convert these fields to a date type...
This is the code:
Dim BirthDate As DateTime = CType(ddlDay.SelectedValue + ddlMonth.SelectedValue + ddlYear.SelectedValue, Date)
And now im here anyways :p ...how can I calculate someones age when I have his birth date?

It would probably be best if you keep the two types the same. Try using this:

Dim BirthDate As DateTime = CType(ddlDay.SelectedValue & "/" & ddlMonth.SelectedValue & "/" & ddlYear.SelectedValue, DateTime)


Try using something like this, for the calculation (assuming a sub, based on a button's click event):

Sub getDiff(Source as Object, E as EventArgs)
Dim myBirth as DateTime
Dim sDate as String
Dim Age As Integer
sDate=ddMonth.SelectedItem.Value & "/" & ddDay.SelectedItem.Text & "/" & ddYear.SelectedItem.Text
myBirth=cDate(sDate)
Age=DateTime.Now.Year - myBirth.Year
If DateTime.Now.Month < myBirth.Month Or (DateTime.Now.Month = myBirth.Month And DateTime.Now.Day < myBirth.Day) Then
Age = Age - 1
End If
lblDate.text="Age=" & Age.ToString
End Sub

Check out full code sample:
http://aspnet101.com/aspnet101/aspnet/codesample.aspx?code=calcage


Hi Peter Smith,

Give the following a try. Example:

Dim tempAsString = ddlDay.SelectedValue + "/" + ddlMonth.SelectedValue + "/" + ddlYear.SelectedValue
Dim birthDateAs DateTime = DateTime.Parse(temp)

The following function can be used to calculate Age, given a BirthDate. Example:

Public Shared Function Age(ByVal dateOfBirth As DateTime) As Integer
If DateTime.Today.Month < dateOfBirth.Month Or DateTime.Today.Month = dateOfBirth.Month And DateTime.Today.Day < dateOfBirth.Day Then
Return DateTime.Today.Year - dateOfBirth.Year - 1
Else
Return DateTime.Today.Year - dateOfBirth.Year
End If
End Function

Hope this helps.

String to DateTime?

If i have this in my Database in a column of VARCHAR

2006/12/28 18:35:10

can i convert it to date time in C# ? I attempted this?

int

result =DateTime.Compare((DateTime)ds2.Tables[0].Rows[0].ItemArray[1], (DateTime)ds2.Tables[0].Rows[1].ItemArray[1]);

which basically is taking two values in that format and comparing them but i get a invalid cast exception. And importing them into SQL As datetime is not possible.

do i have to convert it to an int first? or strip out the "/" and the ":" ? is it even possible?

thanks in advance,

mcm

UseDateTime.TryParse.

Yeah Man,

worked like a charm.

mcm


you can use

Convert.ToDateTime(string)


Convert.ToDateTime produced the same cast error as my other attempt. by TryParse worked.

yay

Wednesday, March 28, 2012

String was not recognized as a valid DateTime

I retrive data from web service. My date is in the format 20/6/2006 0:00. When I try to format date with the following code it gives me above error.

the code is

String.Format("{0:MMMM d, yyyy}",Date.Parse(_landcorReport.vrValuationDate))

please help me

please guys can any one help me?
Hi,
Make sure you are getting valid date in _landcorReport.vrValuationDate. Try using TryParse with an out variable of DateTime type, and then try to format it.

DateTime dt;
bool result = DateTime.TryParse(_landcorReport.vrValuationDate.ToString(), out dt);

Thanks,


unless you are doing Visual J#, you should be usingDateTime.Parse instead

String.Format ( "{0:MMMM d, yyyy}",DateTime.Parse ( _landcorReport.vrValuationDate ) )

that should work assuming of course that _landcorReport.vrValuationDate returns a string that is convertible to a valid date


ReyN:

unless you are doing Visual J#, you should be usingDateTime.Parse instead

String.Format ( "{0:MMMM d, yyyy}",DateTime.Parse ( _landcorReport.vrValuationDate ) )

that should work assuming of course that _landcorReport.vrValuationDate returns a string that is convertible to a valid date

If the input string cannot be converted to DateTime, an exception will be thrown. If you are not sure whether the input string can be converted to datetime, use the TryParse, as this method tries to parse only if the input string is valid and gives you the result if succeeded into the out variable. If you are not using TryParse, you need to use a try {} catch {} block to handle the exception.

Thanks

This method is available in .Net 2.0 while I'm working in .Net 1.1
Hi
Check if the value of_landcorReport.vrValuationDate is a valid date, or use your statement in try catch block

THanks

Saturday, March 24, 2012

Stripping the time portion from date field

Hi all
I've got a textbox on the web page that captures a date.
When an insert is done, the information captured into the database is of the format dd/mm/yyyy hh:mm:ss.
How do I strip the time portion and save only the date part into the database ?
I'm using a formview, sqldatasource controls for this web page.
I tried the following in formview iteminserting event:
Dim culture_2 As System.Globalization.CultureInfo = New CultureInfo("en-GB", True)
Dim wAcceptanceD As TextBox = CType(FormView1.Row.FindControl("dtAcceptDTextBox"), TextBox)
e.Values.Add("dtAcceptD", DateTime.Parse(wAcceptanceD.Text, culture_2, DateTimeStyles.NoCurrentDateDefault))

When I run the web page, I get the following error:

System.ArgumentException was unhandled by user code
Message="Item has already been added. Key in dictionary: 'dtAcceptD' Key being added: 'dtAcceptD'"
Source="mscorlib"
StackTrace:
at System.Collections.Hashtable.Insert(Object key, Object nvalue, Boolean add)

at System.Collections.Hashtable.Add(Object key, Object value)

at System.Collections.Specialized.OrderedDictionary.Add(Object key, Object value)

at Default3.FormView1_ItemInserting(Object sender, FormViewInsertEventArgs e) in C:\SRS\Default3.aspx.vb:line 12

at System.Web.UI.WebControls.FormView.OnItemInserting(FormViewInsertEventArgs e)

at System.Web.UI.WebControls.FormView.HandleInsert(String commandArg, Boolean causesValidation)

at System.Web.UI.WebControls.FormView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup)

at System.Web.UI.WebControls.FormView.OnBubbleEvent(Object source, EventArgs e)

at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)

at System.Web.UI.WebControls.FormViewRow.OnBubbleEvent(Object source, EventArgs e)

at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)

at System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e)

at System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument)

at System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)

at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)

at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)

at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

Can someone pleaseeeeeeeeeeeeeeeee tell me what's wrong ?
TIA.

The problem here is not the date parsing. Well, it is a problem too but not the one you're seeing.
You're using always the same key in your dictionary: "dtAcceptD". The first time it's ok, the second time, it crashes with the error you're seeing. A dictionary can have only one entry with a given key.
As for date parsing, you should specify the date format you're expecting explicitly. There is an overload of ParseExact that takes a format string.
Once you've gotten a DateTime object, it's easy to strip the time part (but why are you asking for it if you're going to throw it away? ) by constructing a new date object from the parts of the old one, something like:
new DateTime(myDate.Year, myDate.Month, myDate.Day)

Hi
Thanks for your reply.
Realised the following:
1) SQL saves the information for a datetime field with date and time information.
2) Viewing the information from the following sources have different results:
From SQL Enterprise Manager, information displayed as dd/mm/yyy.
From SQL Query Analyzer, information displayed as yyyy-mm-dd 00:00:00.
From VS (via the Database Explorer), its displayed as dd/mm/yyyy 12:00:00.
I probably dont need to do any conversion in the ItemInserting event of the formview.
Thanks for the tip on stripping the time portion of a datetime object. I'm sure it will come in handy.