I have product list and every product has create date in DateTime type. I want to take some products that created after my entering time in string type.
I enter EnteredDate in string type, like this format : 05/16/2012
1. var dates = from d in Products
2. where d.CreateDate >= DateTime.ParseExact( EnteredDate, "mm/dd/yy", null )
3. select d;
In second line I got error as String was not recognized as a valid DateTime for "mm/dd/yy".
I also tried DateTime.Parse(), Convert.ToDateTime() and got same error.
How can I filter this product list by create date?
"mm" is minutes, and your year is 4 digits, not 2. You want "MM/dd/yyyy", if your format is really always that. How confident are you on that front? (In particular, if it's entered by a user, you should probably make your code culture-sensitive...)
I would suggest pulling the parsing part out of the query though, and also probably using the invariant culture for parsing if you've really got a fixed format:
DateTime date = DateTime.ParseExact(EnteredDate, "MM/dd/yyyy",
CultureInfo.InvariantCulture);
var dates = Products.Where(d => d.CreateDate >= date);
Call
DateTime.ParseExact(EnteredDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);
Related
So I have a date String coming in with the short date of today.
For Example "1-11-2017"
//Here i convert the HttpCookie to a String
string DateView = Convert.ToString(CurrDay.Value);
//Here i convert the String to DateTime
DateTime myDate = DateTime.ParseExact(DateView, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
After running the code I get the error:
FormatExeption was unhandled by user code
An exception of type 'System.FormatException' occurred in
mscorlib.dll but was not handled in user code
Additional information: String was not recognized as a valid DateTime.
1-11-2017 is not in the format of dd-MM-yyyy, specifically the first part. Use d-M-yyyy instead which will use one digit day and month when the value is below 10 (ie. no 0 padding).
Test:
DateTime myDate = DateTime.ParseExact("1-11-2017", "d-M-yyyy", System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(myDate.ToString());
If you do not know if there will be 0 padding you can pass an array of acceptable formats, the parser will try each one in order they appear in the array.
DateTime myDate = DateTime.ParseExact("1-11-2017", new string[]{"d-M-yyyy", "dd-MM-yyyy"}, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
Fiddle
The Date format ddstands for The day of the month, from 01 through 31. You either supply it as 01-11-2017 or change your formatter to d-MM-yyyy.
Here's a reference to Custom Date and Time Format Strings
I solved this using yyyy-MM-dd instead of dd-MM-yyyy
(and later converting it to normal dates)
Becouse the var always was the day of today the day can be 1 and 2 digits
CurrDay.Value = DateTime.Now.ToString("yyyy-MM-dd" );
// Convert String to DateTime
dateFrom = DateTime.ParseExact(CurrDay.Value.ToString(), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
The comments below helped me find this solution,
Thanks to everyone!
Pass the value like below,
string DateView = Convert.ToString("01-11-2017");
DateTime myDate = DateTime.ParseExact(DateView, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
It's because ParseExact means you pass the format and the method expects the same date format to be passed as string, that's why you need to pass d-MM-yyyy instead of dd-MM-yyyy.
I you're not sure if the passed string will be with one digit or two then do the following:
string[] digits = DateView.split('-');
DateTime dateTime = new DateTime(digits[2], digits[1], digits[0]);
You even can split using / instead, but you need to make sure the first digit is a day and the second is month, and so on.
My advice is pass ticks instead of string of datetime:
DateTime date = new DateTime(numberOfTicks);
string valueAsStr = date.ToString("dd-mm-yyyy");
I want to compare database datetime value that is stored in dd/mm/yyyy format, with the textbox value that is stored in dd-mmm-yyyy format.
I have tired converting the database value to dd-mmm-yyyy format using parseexact-
DateTime dtdb = DateTime.ParseExact(dr["paydate"].ToString(), "dd-MMM-yyyy",null);
and then comparing with the textbox value,
if(dtdb.ToString() != txtpaydate.Text)
But its giving me this error:
String was not recognized as a valid DateTime.
I also tried doing this:
Convert.ToDateTime(dr["paydate"]).ToString("dd-MMM-yyyy")!= txtpaydate.text
but its still giving me the same error. Please let me know how can I solve this issue. Thank you.
you can convert DateTime value and textbox DateTime value to timestamp (from 1970-0-0) then compare it
edited
maybe you want to read rfc3389 about timestamp
You need to parse your textbox into DateTime object and than you can completely free to use general arithmetic operations such as:
if (dtdb > dttb) and etc. If you have any trouble for parsing it, check this page for further information.
If there's any more question, feel free to ask here. But please check stackoverflow before. Have a great day.
string dtdb =dr["paydate"].ToString("dd-MMM-yyyy");
var dt=txtpaydate.Text.ToString("dd-MMM-yyyy");
if(dtdb!= dt)
{
//do what you want
}
As said, it's best to manipulate pure DateTime objects.
You can do it this way:
// Example strings
var myDate1AsString = "31/12/2016";
var myDate2AsString = "31-dec-2016";
// DateTime object used to retrieved the dates as string
var myDate1AsDate = new DateTime();
var myDate2AsDate = new DateTime();
// Parse the strings; if the parse fail, the date is set to DateTime.MinValue
DateTime.TryParseExact(myDate1AsString, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate1AsDate);
DateTime.TryParseExact(myDate2AsString, "dd-MMM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate2AsDate);
// Correctly compare the dates
var result = DateTime.Compare(myDate1AsDate, myDate2AsDate);
// or, directly compare a date with the other.
if (!myDate1AsDate.Equals(myDate2AsDate))
{
// Do some stuff.
}
Always use a CultureInfo when parsing date.
I have following strings in different formats:
16/05/2014
21-Jun-2014
2014-05-16
16-05-2014
5/19/2014
14 May 2014
I need to convert all the above strings into mm/dd/yyyy format in c#.
I have tried used DateTime.ParseExact as DateTime dt = DateTime.ParseExact("16-05-2014", "mm/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture) in C# but i am getting the exception as "String was not recognized as a valid DateTime".
I have also tried to use to Convert.ToDateTime() but it is also not working.
Is there any method or function that we can write/available in C# that would convert the above string formats into a single date format i.e into "mm/dd/yyyy" format ??
Any help on this would be greatly appreciated.
It fails on the very first term of your format string, which is telling the function to treat the "16" as minutes and to look for hours, minutes, and seconds that don't exist in the input.
You have several different date formats, and so need the ParseExact() overload that accepts several different format strings:
string[] formats= {"dd/MM/yyyy", "dd-MMM-yyyy", "yyyy-MM-dd",
"dd-MM-yyyy", "M/d/yyyy", "dd MMM yyyy"};
string converted = DateTime.ParseExact("16-05-2014", formats, CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("MM/dd/yyyy");
Also remember that lower case "m"s are for minutes. If you want months, you need an upper case "M". Full documentation on format strings is here:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Finally, I suspect you are getting ahead of yourself on formatting the output as a string. Keep these values as DateTime objects for as long as possible, and only format to a string at the last possible moment before showing them to the user. If you really do want a string, at least stick with the ISO 8601 standard format.
Your main problem is that your format string is wrong. A small m is for minute, a big M is for month.
Try to pass all your formats in an array. For example like this
DateTime.ParseExact("16-05-2014",
new[] {"dd/MM/yyyy", "dd-MMM-yyyy", "yyyy-MM-dd",
"dd-MM-yyyy", "M/d/yyyy", "dd MMM yyyy"},
CultureInfo.InvariantCulture, DateTimeStyles.None);
With this you can parse all your formats at once.
For more information about the format settings, see the official docs.
Few things:
Your input date 16/05/2014 doesn't match your format Month/Day/Year - how can there be a 16th month?
Secondly, you're using mm which represents Minutes, not Months. You should use MM.
Finally, your sample string 16-05-2014 doesn't match the format provided, you've used hyphens - instead of forward slashes /
Supply a collection of different formats matching your input:
string[] formats = new [] { "MM/dd/yyyy", "dd-MMM-yyyy",
"yyyy-MM-dd", "dd-MM-yyyy", "dd MMM yyyy" };
DateTime dt = DateTime.ParseExact("05-16-2014", formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
You might find the following method useful to accept whatever date format you want and convert it to DateTime:
public DateTime? DTNullable(string DateTimestring, string CurrDateTimeFormat)
{
if (string.IsNullOrEmpty(DateTimestring)) return null;
else
{
DateTime datetimeNotNull;
DateTime.TryParseExact(DateTimestring, CurrDateTimeFormat, null, System.Globalization.DateTimeStyles.None, out datetimeNotNull);
return datetimeNotNull;
}
}
Pass in your desired string to be converted to DateTime along with it's current date time format and this would return you a nullable DateTime. If you're certain that whatever string you're passing in won't be null then you can remove that bit. The reason for it being there is that you can't convert a null to DateTime. In my case I couldn't be certain if it would be or not so I needed the ability to capture nulls as well.
You can use it like this:
DateTime? MyDateTime = DTNullable(MyStartDate, "dd/MM/yyyy");
If you wanted you could alter the method to accept an array of strings and simply iterate through each and return them all in a list if they were of the same format.
As others have pointed out, months are MM not mm (minutes).
On a DateTime object you can call .ToString("MM/dd/yyyy"). Given the strings you have, you can first create new DateTime objects for each string and then call .ToString("MM/dd/yyyy"). For example:
var dateAsMmDdYyyy = DateTime.Now.ToString("MM/dd/yyyy");
I want to retrieve yesterday's date in my ASP.NET web application using C#.
I've tried searching for a solution but have not had much success. The code I'm using just outputs today's date:
string yr = DateTime.Today.Year.ToString();
string mn = DateTime.Today.Month.ToString();
string dt = DateTime.Today.Day.ToString();
date = string.Format("{0}-{1}-{2}", yr, mn, dt);
How can I get yesterday's date?
Use DateTime.AddDays() method with value of -1
var yesterday = DateTime.Today.AddDays(-1);
That will give you : {6/28/2012 12:00:00 AM}
You can also use
DateTime.Now.AddDays(-1)
That will give you previous date with the current time e.g. {6/28/2012 10:30:32 AM}
The code you posted is wrong.
You shouldn't make multiple calls to DateTime.Today. If you happen to run that code just as the date changes you could get completely wrong results. For example if you ran it on December 31st 2011 you might get "2011-1-1".
Use a single call to DateTime.Today then use ToString with an appropriate format string to format the date as you desire.
string result = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");
You don't need to call DateTime.Today multiple times, just use it single time and format the date object in your desire format.. like that
string result = DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd");
OR
string result = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");
You will get yesterday date by this following code snippet.
DateTime dtYesterday = DateTime.Now.Date.AddDays(-1);
var yesterday = DateTime.Now.AddDays(-1);
Something like this should work
var yesterday = DateTime.Now.Date.AddDays(-1);
DateTime.Now gives you the current date and time.
If your looking to remove the the time element then adding .Date constrains it to the date only ie time is 00:00:00.
Finally .AddDays(-1) removes 1 day to give you yesterday.
string result = DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd");
DateTime dateTime = DateTime.Now ;
string today = dateTime.DayOfWeek.ToString();
string yesterday = dateTime.AddDays(-1).DayOfWeek.ToString(); //Fetch day i.e. Mon, Tues
string result = dateTime.AddDays(-1).ToString("yyyy-MM-dd");
The above snippet will work. It is also advisable to make single instance of DateTime.Now;
DateTime.Today as it implies is todays date and you need to get the Date a day before so you subtract one day using AddDays(-1);
There are sufficient options available in DateTime to get the formatting like ToShortDateString depending on your culture and you have no need to concatenate them individually.
Also you can have a desirable format in the .ToString() version of the DateTime instance
I have a single string variable that stores what could be a full date or a partial date:
1) Full Date: 12/12/2010 12:33 AM
2) Partial Date: 12:33 AM (no date field only time)
I'm trying to figure out what would be the best approach to parse the string to figure out if the string is missing the date string or not. The reason is, in my code if the date is missing I will append a default date to the string (such as 1/1/1900). Keep in mind that the time could be in various formats.
Update - My particular answer to this problem.
As all the "posts" have stated, there are multiple answers to this problem, this is ultimately what I used and hope it can help others*:
public DateTime ProcessDateAndTime(string dateString)
{
string dateAndTimeString = dateString;
string[] timeFormats = new string[]
{
"hh:mm tt", "hh:mm:ss tt",
"h:mm tt", "h:mm:ss tt",
"HH:mm:ss", "HH:mm", "H:mm"
};
// check to see if the date string has a time only
DateTime dateTimeTemp;
if (DateTime.TryParseExact(dateString, timeFormats,
CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.None, out dateTimeTemp))
{
// setting date to 01/01/1900
dateAndTimeString = new DateTime(1900, 1, 1).ToShortDateString() + " " + dateString;
}
return DateTime.Parse(dateAndTimeString);
}
*Note: This method is based on the assumption that there are only a specific amount of time formats used in your application, and that it is guaranteed that a properly formatted date and time, or time only string passed in (pre-validation for removal of garbage text).
Use
Convert.ToDateTime(string value, IFormatProviderProvider provider)
Since the string comes in different flavors, provide different format providers as needed.
The order could be:
DateOnly
Time Only
DateTime
The convert will throw an format exception if it fails. If you prefer not to have exceptions, use Datetime.TryParse instead as that returns a boolean.
Depending on how the string is represented you could have more than 3 format providers.
You can try to validate string with a RegEx,
BTW, good regexes for DateTime validation can be found here
Here's one way to do this without knowing all possible time formats:
CultureInfo provider = CultureInfo.CurrentCulture;
DateTime time;
DateTime datetime;
bool isTime = DateTime.TryParse(dateString, provider, DateTimeStyles.NoCurrentDateDefault, out time)
&& time.Date == DateTime.MinValue.Date
&& DateTime.TryParse(dateString, provider, DateTimeStyles.None, out datetime)
&& datetime.Date != DateTime.MinValue.Date);
If the string only has a time then the first TryParse will set the date part to 1/1/0001 or DateTime.MinValue.Date and the second TryParse will set the date part to the current date. This will work unless it is run by Doctor Who after travelling back in time to 1/1/0001.
You can use DateTime.TryParseExact.
This might not be the best but it answers your question:
string dateString = "9:53AM";
if (!dateString.Contains('/')))
{
dateString = DateTime.Now.ToShortDateString() + " " + dateString;
}
Looking at the length of the string will be straight-forward and will support multiple formats. A string with a date and time will most certainly be longer than a string with just a time. However, if your input may have times with high precision (12:30:30:50:20 vs 12/11/11 12:30) and low precision this won't work.
This solution is ideal if you don't need to know the value in the string immediately, and only want to add the default date.
If you support times to the second, for instance, a time will have 8 or less characters and a date-time will have 9 or more.
Given that the time can be in various formats (12/24?) it would be best to user several patterns, in some pre-defined order, trying to parse with each and resolving when the first succeeds.
You can also try
DateTime aTime;
if (DateTime.TryParse(dateString, CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.NoCurrentDateDefault, out aTime))
{
//if the there is no date part in the dateString, date will
// default to Gregorian 1/1/0001
}