473,810 Members | 3,135 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

DateTime Exception

13 New Member
Dear All,

The below mentioned line throw an exception that "The string was not recognized as a valid DateTime. There is an unknown word starting at index 0."

Expand|Select|Wrap|Line Numbers
  1.  DateTime dateTime = DateTime.Parse(date);
  2.  
Actually this error is shown in my home pc where i am using window xp and visual 2010........... .........howeve r in my university lab on window 7 it works fine by passing second parameter as System.Globaliz ation.culturein fo.createspecif icculture("en-US").DateTimeFo rmat.Like:
Expand|Select|Wrap|Line Numbers
  1. DateTime dateTime = DateTime.Parse(date, System.Globalization.CultureInfo.CreateSpecificCulture("en-US").DateTimeFormat);
Please anyone help me regarding this exception.:(

Hope you understand my question.

Thanks,
Feb 19 '12 #1
4 1248
adriancs
122 New Member
for this:

Expand|Select|Wrap|Line Numbers
  1. DateTime dateTime = DateTime.Parse(date);
where do you get the value of this variable "date" in the above statement?
Where does the value come from?
Feb 20 '12 #2
aamersaeed2368
13 New Member
Dear Adriancs,

Please see the below mentioned code actually it is a function which will recursively get the list of files from FTP server.

Expand|Select|Wrap|Line Numbers
  1.  
  2. struct DirectoryItem
  3.     {
  4.         public Uri BaseUri;
  5.  
  6.         public string AbsolutePath
  7.         {
  8.             get
  9.             {
  10.                 return string.Format("{0}/{1}", BaseUri, Name);
  11.             }
  12.         }  
  13.         public DateTime DateCreated;
  14.         public bool IsDirectory;
  15.         public string Name;
  16.         public List<DirectoryItem> Items;
  17.     }
  18.  
  19. public List<DirectoryItem> GetDirectoryInformation(string address, string username, string password)
  20.         {
  21.             FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(address);
  22.             request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
  23.             request.Credentials = new NetworkCredential(username, password);
  24.             request.UsePassive = true;
  25.             request.UseBinary = true;
  26.             request.KeepAlive = false;
  27.  
  28.             List<DirectoryItem> returnValue = new List<DirectoryItem>();
  29.             string[] list = null;
  30.  
  31.             using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
  32.             using (StreamReader reader = new StreamReader(response.GetResponseStream()))
  33.             {
  34.                 list = reader.ReadToEnd().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
  35.             }
  36.  
  37.             foreach (string line in list)
  38.             {
  39.                 // Windows FTP Server Response Format
  40.                 // DateCreated    IsDirectory    Name
  41.                 string data = line;
  42.  
  43.                 // Parse date
  44.                 string date = data.Substring(0,17);
  45.                 DateTime dateTime = DateTime.Parse(date);
  46.  
  47.                 data = data.Remove(0, 24);
  48.  
  49.                 // Parse <DIR>
  50.                 string dir = data.Substring(0, 5);
  51.                 bool isDirectory = dir.Equals("<dir>", StringComparison.InvariantCultureIgnoreCase);
  52.                 data = data.Remove(0, 5);
  53.                 data = data.Remove(0, 10);
  54.  
  55.                 // Parse name
  56.                 string name = data;
  57.  
  58.                 // Create directory info
  59.                 DirectoryItem item = new DirectoryItem();
  60.                 item.BaseUri = new Uri(address);
  61.                 item.DateCreated = dateTime;
  62.                 item.IsDirectory = isDirectory;
  63.                 item.Name = name;
  64.  
  65.  
  66.                 // Debug.WriteLine(item.AbsolutePath);
  67.  
  68.                 item.Items = item.IsDirectory ? GetDirectoryInformation(item.AbsolutePath, username, password) : null;
  69.  
  70.                 f.listboxFiles.Items.Add(name);
  71.  
  72.                 returnValue.Add(item);
  73.             }
  74.  
  75.             return returnValue;
  76.         }
And call to this function is
Expand|Select|Wrap|Line Numbers
  1. List<DirectoryItem> listing = GetDirectoryInformation(ftptxtbox.Text, "anonymous", "anonymous");
Feb 20 '12 #3
adriancs
122 New Member
you can create your own string to DateTime converter. Create a function like this:

Expand|Select|Wrap|Line Numbers
  1. public static DateTime GetDateTime(string date)
  2. {
  3.     // assume that
  4.     // date = "2012-02-21 21:29:30";
  5.     int year = Convert.ToInt32(data.Substring(0, 4));
  6.     int month = Convert.ToInt32(data.Substring(5, 2));
  7.     int day = Convert.ToInt32(data.Substring(8, 2));
  8.     int hour = Convert.ToInt32(data.Substring(11, 2));
  9.     int minute = Convert.ToInt32(data.Substring(14, 2));
  10.     int second = Convert.ToInt32(data.Substring(17, 2));
  11.     return new DateTime(year, month, day, hour, minute, second);
  12. }
or
Expand|Select|Wrap|Line Numbers
  1. public static DateTime GetDateTime(string date)
  2. {
  3.     // assume that
  4.     // date = "2012-02-21-21-34-30";
  5.     string[] sa = data.Split('-');
  6.     int[] ia = new int[sa.Length];
  7.     for (int i = 0; i < sa.Length; i++)
  8.     {
  9.         ia[i] = Convert.ToInt32(sa[i]);
  10.     }
  11.     return  new DateTime(ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]);
  12. }
or
Expand|Select|Wrap|Line Numbers
  1. public static DateTime GetDateTime(string date)
  2. {
  3.     // assume
  4.     // date = "21 Feb 2012, 09:42 PM";
  5.     string[] sa = date.Split(',');
  6.     string[] separator1 = new string[] { " " };
  7.     string[] sb = sa[0].Trim().Split(separator1, StringSplitOptions.None);
  8.  
  9.     int day = Convert.ToInt32(sb[0]);
  10.  
  11.     int month = 0;
  12.  
  13.     switch (sb[1].ToUpper())
  14.     {
  15.         case "JAN":
  16.             month = 1;
  17.             break;
  18.         case "FEB":
  19.             month = 2;
  20.             break;
  21.  
  22.         .....
  23.  
  24.         default:
  25.             break;
  26.     }
  27.  
  28.     int year = Convert.ToInt32(sb[2]);
  29.  
  30.     string[] sc = sa[1].Split(':');
  31.  
  32.     int hour = Convert.ToInt32(sc[0]);
  33.  
  34.     string[] sd = sc[1].Split(separator1, StringSplitOptions.None);
  35.  
  36.     int minute = Convert.ToInt32(sd[0]);
  37.  
  38.     if (sd[1].ToUpper() == "PM")
  39.         hour += 12;
  40.  
  41.     return new DateTime(year, month, day, hour, minute, 0);
  42. }
then,
Expand|Select|Wrap|Line Numbers
  1. DateTime dateTime = GetDateTime(date);
Feb 21 '12 #4
adriancs
122 New Member
...repeated post. can be deleted.
Feb 21 '12 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

15
6990
by: Dan S | last post by:
My application asks the user to enter in a date - in the mm/dd/yyyy format. Is there any quick and easy way to verify the date the user enters is formatted correctly? Right now I'm calling DateTime.Parse() and catching the FormatException but it seems this is a bit inefficient - catching the exception that is. There is some pretty obvious delay while it traces back up the call stack. Is there a better way? Something that returns a bool...
4
18173
by: Hans Merkl | last post by:
Does anybody know of a library that can handle strings pf various formats and conver them to a DateTime value? The strings are coming from a webform and I can't restrict the input (it's not my form). I have been using Convert.ToDateTime but it choked on "12:00 noon". I am looking for a function that can make sense out of anything that looks like a date/time. Outlook is pretty good at it when you enter an appointment with the GUI, but...
1
2519
by: adolf garlic | last post by:
I'm having a problem with dates. (No not the sort that you have at christmas) I have a webform with a text box and a calendar control. You can either - enter a date manually (we are talking uk style here dd/mm/yyyy) in the textbox - click a date on the calendar which puts the date value in the textbox (uk style)
0
459
by: Glenn Venzke | last post by:
I have an aspx page that is set up to copy backed-up DB files from a shared directory to a local folder. For some reason, it is being denied access to the network share. I have the web app running under a domain account that I know for a fact has access. it works fine when I log on to the network and browse the directory manually. Even when I grant full control to everyone on the share and the underlying folder itself, I still can't access...
3
2223
by: news.microsoft.com | last post by:
dim d as datetime d = DateTime.Parse(#6/10/2004 11:50:40 PM#) produces exception "String was not recognized as a valid DateTime." d = DateTime.Parse("6/10/2004 11:50:40 PM") is OK d = DateTime.Parse(#6/10/2004 11:50:40 AM#) is OK can somebody expain what is wrong with the first statement I am using VS 2003 with framework version 1.1 sp1 Thanx George
11
7258
by: Cor Ligthert | last post by:
Hello everybody, Jay and Herfried are telling me every time when I use CDate that using the datetime.parseexact is always the best way to do String to datetime conversions. They don't tell why only that I have to listen to them because they know it better. They told also that in a business situation it is better to use datetime.parseexact for changing cultures and not to use the globalization setting. I did not give them this sample,...
11
2813
by: Tim | last post by:
Hi, I am trying to do something simple. Convert a string date to datetime but it is not working and is giving me a baffling error! System.Convert.ToDateTime("Jan 30, 2006") 'System.Convert.ToDateTime("Jan 30, 2006")' threw an exception of type 'System.IndexOutOfRangeException' base {System.SystemException}: {"Index was outside the bounds of the array."}
5
51682
by: GG | last post by:
I am trying to add a nullable datetime column to a datatable fails. I am getting exception DataSet does not support System.Nullable<>. None of these works dtSearchFromData.Columns.Add( new DataColumn( "StartDate", typeof( DateTime? ) ) ); dtSearchFromData.Columns.Add( new DataColumn( "EndDate", typeof( System.Nullable<DateTime>) ) ); Any ideas?
11
303
by: =?Utf-8?B?UGFvbG8=?= | last post by:
I have a SQL database table with rows in which the primary key is a DateTime type (although I don't use the Time part). Have added numerous rows and now want to delete one so I enter the date (dd/mm/yyyy) for a row I know is in the database but my app tells me that no row exists for that date. Am I missing something in relation to this data type?
3
3384
by: csharpula csharp | last post by:
Hello, I am trying to add DataTime.Now.ToString() to a file name but I get an exception while doing it that such format is not supported in path. How can I solve this and cast this issue? Thank you! *** Sent via Developersdex http://www.developersdex.com ***
0
9722
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9603
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10644
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10379
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10393
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9200
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5690
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3863
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3015
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.