I am trying to check if the selected month is already past.
if (Convert.ToDateTime(DDMonths.SelectedItem.Text).Month > DateTime.Now.Month)
{
//logic here if date is not in the past
}
DDMonths.SelectedItem.Text value is April
However I am getting the following Format exception error:
String was not recognized as a valid DateTime.
You can parse the month by name with the following:
DateTime.ParseExact(DDMonths.SelectedItem.Text, "MMMM", CultureInfo.CurrentCulture ).Month
However, you'd be better off making the Value of each element in DDMonths the integer value corresponding to the month instead, if possible.
Convert.ToDateTime cannot understand your date format, you need to use DateTime.ParseExact instead:
if(DateTime.ParseExact(DDMonths.SelectedItem.Text, "MMMM", CultureInfo.CurrentCulture).Month > DateTime.Now.Month) {
...
}
it means that your line
Convert.ToDateTime(DDMonths.SelectedItem.Text)
is giving you error. You should use
DateTime.ParseExact(DDMonths.SelectedItem.Text,"MMMM",CultureInfo.InvariantCulture);
So the Text of your DropDownList-Item is not convertible to DateTime with the current culture. So maybe you are showing the month-name (what i assume) or the error is more subtiel. You could use the ListItem.Value to store the datetime in a specific format, for example:
"yyyyMMdd" -> "20130726"
Then you can parse it in this way:
var dt = DateTime.ParseExact("20130726", "yyyyMMdd", CultureInfo.InvariantCulture);
If you want to allow the monthname:
dt = DateTime.ParseExact("July", "MMMM", CultureInfo.InvariantCulture);
Since you are just looking for the number of the month, why parse it to a DateTime at all? You can just get it from the DateTimeFormatInfo directly:
string input = "April";
var months = DateTimeFormatInfo.CurrentInfo.MonthNames;
var monthNumber = 1 + Array.FindIndex(months, x => x.Equals(input, StringComparison.CurrentCultureIgnoreCase));
if (monthNumber > DateTime.Now.Month)
{
// ...
}
Do think about what you want to do if it is currently April. Depending on what you are doing, you may want to compare using >=.
Also, if you are writing a desktop application, this code (and the others) are just fine. But if you are writing a web application and this code is running server-side, then you have two additional concerns:
The culture should match the input. You may need to use a different culture, or the InvariantCulture.
You are comparing to DateTime.Now - which will be in the server's time zone. So if a user in another part of the world uses this on the 1st of their new month while your server is still on the prior day, then your comparison will fail.
You should be using a ParseExact variant of DateTime
DateTime.ParseExact("April", "MMMM", CultureInfo.InvariantCulture).Month // outputs 4
you should also try using the Value (DDMonths.SelectedItem.Value) component and fill it as needed
Related
In my code I need to handle two types of datetime formats. if the input date is a like 8/31/2017 12:00:00 AM I just wanna save it. But when it comes with the format like "25.11.13" I wanna convert it like this 11/25/2013 12:00:00 AM and wanna save it.
Somehow I managed my code but the problem is the "else block" is not working as expected (actually it won't work at all).
DateTime registrationDate = new DateTime();
if (DateTime.TryParse(myTable.Rows[i][6].ToString(), out registrationDate))
{
record.RegistrationDate = !string.IsNullOrEmpty(detailsTable.Rows[i][6].ToString()) ? Convert.ToDateTime(detailsTable.Rows[i][6].ToString()) : (DateTime?)null;
}
else
{
DateTime.TryParse(detailsTable.Rows[i][6].ToString(), out registrationDate);
record.RegistrationDate = registrationDate;
}
I think you have a culture issue here. "8/31/2017" is clearly in US format M/D/Y because no month has 31 days. However "25.11.13" is in another D/M/Y (possibly UK) format.
Unless your detailsTable contains the culture the value is in you are stuck here. This is because it is impossible to tell if 9/11/2001 is the 9th of November or 11th of September without further information.
DateTime.TryParse will try to use the culture of the user that is running the code. Note if it is a web site then it runs as the account the IIS Service is set to use. There is an overload of TryParse that takes another parameter that allows you to tell it which culture the supplied string is in.
If you know that all dates that have slashes '/' are in US format and all dates that have dots '.' are in UK format then you can pre-parse the string to enable you to tell TryParse the correct culture. Like this:
static DateTime Parse(string input)
{
CultureInfo ci =
CultureInfo.CreateSpecificCulture(
input.Contains(".") ?
"en-GB" :
"en-US");
DateTime result;
DateTime.TryParse(input, ci, DateTimeStyles.None, out result);
return result;
}
Is there any possible way for saving DateTime.Now to ddMMyyyy format without using ToString(). Because whenever I use the string operation the statement is not accepted by entity framework. I need to add DateTime to DB in date format of ddMMyyyy. Is there any way??
It would be silly and counterproductive to store dates as "ddMMyyyy". First of all you'd need a varchar(8), not a DATE or DATETIME.
On top of that, how are you ever going to sort it using ORDER BY, or use BETWEEN queries, or do myDate > someValue / myDate < someValue queries? You can't with a date-string formatted like that.
Also a notation such as "ddMMyyyy" is a User Interface representation of an underlying value. Databases should almost never store User Interface representations, that is a job for the... you guessed it... User Interface.
Best to just forget about it, or else be ready to face the horrible consequences.
Change you SQL Server Database data type from "datetime" to "date" ?
From the article for the DateTime.Parse() method (MSDN Article)
So you can do:
var dateTime = DateTime.Parse("01012001");
Which will give you a DateTime typed object.
If you need to specify which date format you want to use, you would use DateTime.ParseExact (MSDN Article)
Which you would use in a situation like this (Where you are using a British style date format):
string[] formats= { "ddMMyyyy" }
var dateTime = DateTime.ParseExact("01012001", formats, new CultureInfo("en-US"), DateTimeStyles.None);
The format "ddMMyyyy" (or any other format) makes any sense only if we're talking about strings.
If you need only the day, month, and year in the program you can still use the DateTime class.
You simply ignore the other properties like minutes, hours, etc...
DateTime now = DateTime.Now;
Method(now.Day, now.Month, now.Year);
or
DateTime emptyDateTime = new DateTime();
// in this case emptyDateTime values are the following:
emptyDateTime.Year: 1
emptyDateTime.Month: 1
emptyDateTime.Day: 1
emptyDateTime.Hour: 0
emptyDateTime.Minute: 0
emptyDateTime.Second: 0
I'm trying to display a time value but in a special format. For instance, if my variable contains 07:25:00, I'd like to display it like that :
07H25
I tried to read some things about custom formats but I didn't get anything interesting. Any idea about a way to do that?
You could use a formater for it. For sample, try to have a CultureInfo object (you could clone the current) which allows you to specify the globalization configurations and change the DateTimeFormat.TimeSeparator property. For sample:
CultureInfo currentCulture = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
currentCulture.DateTimeFormat.TimeSeparator = "H";
string date = DateTime.Now.ToString("hh:mm", currentCulture);
If your variable a DateTime, you can easily use custom date and time format with string delimiter like;
date.ToString("HH'H'mm")
If your variable a TimeSpan, you can easily use custom date and time format with string delimiter like;
ts.ToString("hh'H'mm")
If your variable a string, you can parse it to TimeSpan first then format it like;
TimeSpan ts = TimeSpan.Parse("07:25:00", CultureInfo.InvariantCulture);
ts.ToString("hh'H'mm")
DateTime now = DateTime.Now;
Console.WriteLine("Time: " + now.ToString("HH\\Hmm"));
output is
Time: 15H44
and HH denotes a 24hr Time format so you will get 07, not just 7
Here is a reference table for all DateTime format strings.
Adding onto the other answers already given, this should give you enough information to go away and sort out time format to whatever you desire.
I want to convert date to a specific format (e.g. en-US MM/dd/yyyy) and I am aware about normal method to parse it.
But in my case I'm unaware about the source date format. Source date format is subject to change as per server environment. It can be en-US or en-GB.
e.g. DateTime dt = DateTime.Now;
'dt' can be '27/03/2014' or '03/27/2014'.
How to convert the source date to en-US format if I don't know source date format?
(string format would be fine - MM/dd/yyyy e.g. "03/27/2014").
If you don't know the source format, there is a chance of getting errors while trying to convert. For example, try converting:
05/01/2013
A computer wouldn't be able to identify the date in such a case. It could result in two outputs: 05 Jan, 2013 or 01 May, 2013.
DateTime.Now.toString("yyyy-MM-dd"); //toString(specify format)
try this one
DateTime result;
if (!DateTime.TryParseExact(inputString, "dd/MM/yyyy", out result)
result = DateTime.ParseExact(inputString, "MM/dd/yyyy");
OR
DateTime result;
if (!DateTime.TryParse(inputString, out result)
result = DateTime.ParseExact(inputString, CultureInfo.InvariantCulture, DateTimeStyles.None);
If you know your environment will always be the deciding factor, why not just use that?
Try some variation of the following:
string yourFormat = ... // Whatever is your default format
if(Thread.CurrentThread.CurrentCulture.Name == "en-US")
{
yourFormat = "MM/dd/yyyy";
}
else (if Thread.CurrentThread.CurrentCulture.Name == "en-GB")
{
yourFormat = "dd/MM/yyyy";
}
DateTime d = DateTime.ParseExact(inputString, yourFormat, null)
How to convert the source date to en-US format if I don't know source date format?
You need to know the source date format, only then can you convert it to the required date format.
As wiero has rightly said in the comments "If you have 01/02/2014 depending its 1 February or 2 January. You have to know how to read it".
The default format of the object returned by DateTime.Now will be the one specified in your server setting, check the screenshot below:
Referring to #DarkWanderer's comment in question:
DateTime object has nothing to do with format.
Just needed to convert it to the specific format using ToString("MM/dd/yyyy").
I was using Parse() method to convert but it will not work. BToString() method is surely a way.
This will work: dt.Tostring("MM/dd/yyyy");
Thanks #DarkWanderer.
I saw a lot of answers, most of which include using of DateTime.ParseExact and "CultureInfo.InvariantCulture` but it's not working for me and I'm not sure that those answers are 100% related to the problem I need to solve.
I have table with records from the database. The use can perform search based on different criteria one of which is date. I use some inherited jQuery calendar and in my controller the data from the date filed comes in format "dd/mm/yyyy hh:mm:ss". I want to be able to use this information to perform search in the database for records on the same date. The one problem is that I want to use only the date but not the time, but I'm not sure in what order to solve this problem so I decided to convert the incoming string to valid MS SQL datetime and see what happen and the to think about the time.
I tried different things, this is my last after which I decide to post here :
if (!String.IsNullOrEmpty(selDate))
{
CultureInfo myCItrad = new CultureInfo("bg-BG", false);
DateTime parsedDate = DateTime.ParseExact(
selDate,
"dd.MM.yyyy hh:mm:ss",
myCItrad);
model = model.Where(m => m.Date == parsedDate);
}
when I parse selDate the string doesn't contain them, it's - "23/05/2013 09:04:45"
If your input string looks like "23/05/2013 09:04:45" then you should use this pattern for ParseExact: "dd/MM/yyyy hh:mm:ss"
if (!String.IsNullOrEmpty(selDate))
{
CultureInfo myCItrad = new CultureInfo("bg-BG", false);
DateTime parsedDate = DateTime.ParseExact(
selDate,
"dd/MM/yyyy hh:mm:ss",
myCItrad);
model = model.Where(m => m.Date == parsedDate);
}
Leron,
Date issues between application and SQL are well known.
SQL and .NET date time types are different:
http://msdn.microsoft.com/en-us/library/system.data.sqltypes.sqldatetime.aspx
On both SQL and .NET there are numerous date time formats, all need to be treated as numbers types.
So, you need to know how to convert numerous date time formats on .NET side, to convert it to SQL type, and vice versa. Not a good practice...
Use SqlDateTime to conduct conversion.
Or:
A simple, a bit "dirty" solution, is something like that:
Take the date wanted by user. Calculate how many days is it from
current (e.g. --> int days = (DateTime.Now-selectDate).Days;
Now on database query, do it using SQL: GetDate()-days
The one problem is that I want to use only the date but not the time,
This has nothing to do with SQL date formats.
If you want to use only the date and not the time, you could do something like:
model = model.Where(m => m.Date.Date == parsedDate.Date);
or if you prefer:
model = model.Where(m => (m.Date >= parsedDate.Date && m.Date < parsedDate.Date.AddDays(1));
In the above m.Date.Date and parsedDate.Date you are using the DateTime.Date property to get the date component of your date value, discarding the time component.
DateTime in SQL is this format yyyy-MM-dd HH:mm:ss. correct code is
DateTime parsedDate = DateTime.ParseExact(selDate, "yyyy-MM-dd" myCItrad);