I have Window 7 installed in my computer. The problem is that the system date format is changed some time if computer is restarted. I need to make the date format fixed but don't know how. I have application built in mvc 3 and have code for string to datetime conversion. If system datetime format doesn't match with string it show error that
string is not in proper format for converting into datetime which looks for system datetime. The exception is thrown in following code:
DateTime startDate = Convert.ToDateTime(start);
where,
string start = sundayOfLastWeek.ToString("MM/dd/yyyy HH:mm:ss");
Or, Is there any alternatives so that I can change in code that works all the time despite the system Date Time.
Use DateTime.ParseExact with the format "MM/dd/yyyy HH:mm:ss"
startDate = DateTime.ParseExact(start,
"MM/dd/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
EDIT: based on comment from #John Woo
You can pass string array to DateTime.Parse like:
string[] dateFormats = new string[] { "MM/dd/yyyy HH:mm:ss", "dd/MM/yyyy HH:mm:ss", "d/MM/yyyy" };
DateTime startDate = DateTime.ParseExact(start,
dateFormats,
CultureInfo.InvariantCulture,
DateTimeStyles.None);
use .ToString(CultureInfo.InvariantCulture) and Parse(value, CultureInfo.InvariantCulture) for values persistance. Only omit CultureInfo if you render values for display purpose. For some specific data formats special formatting rules may exist - follow them.
to recover your data use ParseExact.
As Habib already answered:
//Add any format you want or expect
string[] formats = { "MM/dd/yyyy HH:mm:ss", "dd.MM.yyyy HH:mm:ss" };
DateTime startDate = DateTime.ParseExact(start, formats,
System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
It should help.
Related
I have two Timestamps that are saved to and read from two XML files.
Currently I am reading the timestamps from the xml files in a WCF Service method, so they are coming in as Strings , but I need them to be converted into DateTime so they can be compared.
The obvious Convert.ToDateTime(TimeStampString) renders this error at Runtime -
String was not recognized as a valid DateTime
As does
DateTime.ParseExact(TimeStampString, "mm/dd/yyyy hh:MM:ss", CultureInfo.InvariantCulture);
Both Timestamps are in the correct format for DateTime (mm/dd/yyyy hh:MM:ss).
I've even tried splitting the timstamp strings into String[] and assembling my own DateTime object by hand, and I still received the error.
Is this a format issue? How can I make my String a valid DateTime?
It's a format issue
mm/dd/yy hh:MM:ss
should be
MM/dd/yyyy hh:mm:ss
(basically, swap the upper case MM in the date & the lowercase mm in the time)
I resolved the issue by removing any attempts to alter the format from US, so Strings came in with US format - then used an IFormatProvider to alter the format at conversion time.
IFormatProvider localFormat = new System.Globalization.CultureInfo("fr-FR", true);
DateTime ContentLastUpdatedTime = DateTime.Parse(ContentLastUpdatedStamp, localFormat , System.Globalization.DateTimeStyles.AssumeLocal);
DateTime ContentLastGrabbedTime = DateTime.Parse(LastGrabbedTimeStamp, localFormat , System.Globalization.DateTimeStyles.AssumeLocal);
You need to use
DateTime.ParseExact(TimeStampString, "MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture);
instead of
DateTime.ParseExact(TimeStampString, "mm/dd/yyyy hh:MM:ss", CultureInfo.InvariantCulture);
The issue is lower case mm which is used for minutes, You need MM upper case MM, plus your date is in 24 hours format, and you need upper case HH for hour part , so your format should be:
MM/dd/yyyy HH:mm:ss
(considering you have yyyy in your original code based on your comment)
See: Custom Date and Time Format Strings
Here you go
var dtedatetime = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz");
DateTimeOffset dto;
bool bIsParsed = DateTimeOffset.TryParseExact(dtedatetime , "yyyy'-'MM'-'dd'T'HH':'mm':'sszzz",
System.Globalization.CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal, out dto);
var result = dto.DateTime;
I have a custom date format that I want to convert to Datetime so I can then insert into my database, I tried using Datetime.ParseExact() But I think I'm misunderstanding something as the code throws a System.FormatException.
I have the following date format from a csv
> 6/11/2014 9:00
and I wish to convert it to the mysql datetime format
> 0000-00-00 00:00:00 OR yyyy-MM-dd HH:mm:ss
Notice they haven't included the seconds in the original date so I am unsure (without appending them to the end) how to set all records to just have "00" for seconds as it is not available.
I tried the following which throws an exception
DateTime myDate = DateTime.ParseExact("6/11/2014 9:00", "yyyy-MM-dd HH:mm",
System.Globalization.CultureInfo.InvariantCulture);
first thing you need to convert string to date time and than convert datetime tos tring
string strd = "6/11/2014 9:00";
DateTime dt ;
//convert datetime string to datetime
if(DateTime.TryParse(strd, out dt))
{
//convert datetime to custom datetime format
Console.WriteLine("The current date and time: {0: yyyy-MM-dd HH:mm:ss}",
dt); ;
}
output
I know this is late to answer that but I'm really surprised none of answer consider to use IFormatProvider to prevent a possible parsing error because of / format specifier or considering your string is a standard date and time format for your CurrentCulture or not so you can or can't use DateTime.TryParse(string, out DateTime) overload directly.
First of all, let's look at what DateTime.ParseExact documentation says:
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly or an exception is thrown.
In your case, they don't match. You should use d/MM/yyyy H:mm format to parse your example string with a culture that have / as a DateSeparator. I almost always suggest to use DateTime.TryParseExact method in this kind of situations;
string s = "6/11/2014 9:00";
DateTime dt;
if(DateTime.TryParseExact(s, "d/MM/yyyy H:mm", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss"));
// result will be 2014-11-06 09:00:00
}
If you know formats of your dates, then you can do this:
string stringDate = "6/11/2014 9:00";
//Your date formats of input
string[] dateFormats = new string[]
{
"d/MM/yyyy H:mm",
"dd/MM/yyyy H:mm",
"dd/MM/yyyy HH:mm",
"dd/MM/yyyy H:mm:ss",
"dd/MM/yyyy HH:mm:ss"
/* And other formats */
};
DateTime convertedDate;
bool isSuccessful = DateTime.TryParseExact(stringDate, dateFormats,
System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out convertedDate);
if (isSuccessful)
{
//If conversion was successful then you can print your date at any format you like
//because you have your date as DateTime object
Console.WriteLine(convertedDate.ToString("dd-MM-yyyy HH:mm:ss")); /* Or other format you want to print */
}
I hope it will be helpful to you.
I have a database script that returns date time string and my problem is that I don't know what format my string will be. The reason is that I have desktop in different culture and they could return any kind of format. My ultimate goal is, from the string to return the DateTime.
As I am trying to write something I am realizing that I would need to try any kind of format to make sure something comes back to me without an exception.
There should be a better way to do this without trial and error.
This is what I have but it only works for a few formats:
public static DateTime FromQueryResultString(string dttmString)
{
string[] formats = { "dd/MM/yyyy", "yyyy-MM-dd HH:mm:ss", "dd/MM/yyyy HH:mm:ss", "yyyyMMdd HH:mm:ss", "dd.MM.yy hh:mm", "M/d/yy h:mm tt", "ddd MMM dd H:mm:ss yyyy", "dd.MM.yy hh:mm", "dd.MM.yy HH:mm","ddd MMM yy H:mm:ss yyyy" };
string name = Thread.CurrentThread.CurrentCulture.Name;
IFormatProvider format = new CultureInfo(name, false);
DateTime formattedDate = DateTime.ParseExact(dttmString, formats, format, DateTimeStyles.None);
}
Try this:
DateTime parsedDate;
if(DateTime.TryParse(dttmString, parsedDate))
{
//TODO
}
I think you're missing a fundamental concept.
Considering that you're talking about a DataBase script, it' a script, I immagine, which returns a data from database. Your database has to always hold a DateTime, floating point numbers and other culture sencitive data in one common format. In this case, you will have one single stable Data Access Layer which will recover and manipulates data recovered from Rome, Paris, Beijing or Abu Dhabi. The client program that data will visualize in culture dependent way.
In short: choose one format and store it in that way.
It's clear that this architecture is not always possible to have, but from my expirience it is possible in 99% of cases.
Hope this helps.
You can get the current culture set up via the CultureInfo.CurrentCulture property. Then you can get the date time format from the CultureInfo return object's Property DateTimeFormat. This means that Windows handles it and you do not have to do any special manual handling.
EDIT: Sample Code
public static DateTime FromQueryResultString(string dttmString)
{
string[] formats = { "dd/MM/yyyy", "yyyy-MM-dd HH:mm:ss", "dd/MM/yyyy HH:mm:ss"
IFormatProvider format = Thread.CurrentThread.CurrentCulture.DateTimeFormat;
DateTime formattedDate = DateTime.ParseExact(dttmString, formats, format, System.Globalization.DateTimeStyles.None);
}
string dt = "10/25/2010 11:40:05 PM";
var currentThread = Thread.CurrentThread.CurrentCulture; //ru-RU
DateTime dateTime = DateTime.Parse(dt); //Exception!
How to parse that dt?
UPDATE:
In my case DateTime can be represent as "25.10.2010 11:40:05" or "10/25/2010 11:40:05 PM"
Is these any "generic" method to parse it without changing CurrentCulture?
Use a custom Date and Time format string, using either ParseExact or TryParseExact.
DateTime dateTime;
DateTime.TryParseExact(
dt,
"MM/dd/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dateTime
);
The string cannot be parsed as a Russian DateTime representation since the Russian culture doesn't use AM/PM, hence the use of the use of CultureInfo.InvariantCulture which is a US like culture (it represents no specific culture, but is modeled after the en-US one).
Try using ParseExact instead:
DateTime myDate = DateTime.ParseExact("10/25/2010 11:40:05 PM", "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
Try DateTime.Parse(dt, CultureInfo.GetCultureInfo("EN-us"))
var result = DateTime.ParseExact(dt,
"MM/dd/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture);
To avoid runtime exceptions use safe DateTime.TryParseExact() method, it returns false in case of unsuccessfull parsing rather than throwing the FormatException exception
Russia doesn't use AM and PM as their AM/PM designators, which is at least one reason that would fail. Another is that Russia may not use the "month/day/year" format which is mostly a peculiarity of the US as far as I'm aware. (I can't remember Russia's format strings offhand; I do remember that the genitive month names caused me grief recently, but that's another story...)
I would personally explicitly specify the culture as the invariant culture, and also explicitly specify the format string:
string text = "10/25/2010 11:40:05 PM";
string pattern = "MM/dd/yyyy hh:mm:ss tt";
DateTime dt = DateTime.ParseExact(text, pattern,
CultureInfo.InvariantCulture);
If this might reasonably be expected to fail, you should use DateTime.TryParseExact instead, to handle failure gracefully without involving exceptions.
Try something like this:
dateTime = DateTime.Parse(dt, CultureInfo.CreateSpecificCulture("en-US"));
i receive this date: 9/20/2010 3:32:32 PM
i need to convert to datetime.
i try:
DateTime DateFrom = DateTime.ParseExact("9/20/2010 3:32:32 PM", "dd/M/yyyy", CultureInfo.InvariantCulture);
but i get error: String was not recognized as a valid DateTime.
in my computer the region is: Hebrew (Israel) dd/MM/yyyy for short date and hh:mm for short time
how to fix it ?
thank's in advance
If you're receiving "9/20/2010 3:32:32 PM" as a string, then trying to parse it as if it were in the "dd/MM/yyyy" format is clearly wrong - that's try to use a month of 20. You're also only parsing part of the string - you need to either trim your string or provide the complete format.
Try this:
DateTime dateFrom = DateTime.ParseExact("9/20/2010 3:32:32 PM",
"M/dd/yyyy h:mm:ss tt",
CultureInfo.InvariantCulture);
Note that using this sort of strict parsing will only work if you can guarantee that that will always be the format. Where are you getting this data from?
How could it work man.You are converting into "dd/MM/yyyy " & putting month as 20.In your
question dd/M/yyyy is wrong.It will like dd/MM/yyyy.
By default format is MM/DD/yyyy.
simple way to do .......
DateTime DateFrom = DateTime.Parse("9/20/2010 3:32:32 PM");
if you want to provide a specific Format so use like that
DateTime DateFrom = DateTime.ParseExact("20/09/2010 3:32:32 PM", "dd/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
I hope it works.
It looks like your original date string is in a US format (i.e. m/dd/yyyy). Try replacing your third parameter with new CultureInfo("en-US")
DateTime dateFrom = DateTime.ParseExact("9/20/2010 3:32:32 PM", "M/dd/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
Works for me
I wouldn't use ParseExact() when I know that time string is formatted by invariant culture.
DateTime dateFrom = DateTime.Parse(dateString, CultureInfo.InvariantCulture);
is both more compact and more clear.