I have a program that has synchronization. That means I need to save the last synchronization date and check if it needs to be synchronized.
So, I have this:
IS.SaveContactsRetrieveDate(DateTime.Now.ToString("dd.MM.yyyy"));
Saving a date to Isolated Storage.
Then, when I call IF:
DateTime toDate = DateTime.Now;
string contactsRetriveDate = IS.ReadContactsRetriveDate();
if (contactsRetriveDate == "" || DateTime.Compare(toDate, DateTime.Parse(contactsRetriveDate)) == 1)
{
MessageBox.SHow("");
}
The problem is that when user changes the region code fails here:
DateTime.Compare(toDate, DateTime.Parse(contactsRetriveDate))
With incorrect input error.
I understand that Latvian format is dd.MM.yyyy and USA MM/dd/yyyy - but I can't find a solution...
I need all datetime parsed in one format, so I could add days, weeks and compare date.
You should serialize and deserialize your date in a culture-independent manner (where "d" is the "Short date pattern" of the Standard Date and Time Format Strings):
var s = DateTime.Now.ToString("d", CultureInfo.InvariantCulture);
var d = DateTime.Parse(s, CultureInfo.InvariantCulture);
You can use ParseExact
DateTime.ParseExact(datestring, "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);
you already know format so you can go for this, but make sure the string is in same format and never changes.
u can try this one:
DateTime toDate = DateTime.Now;
string contactsRetriveDate = IS.ReadContactsRetriveDate();
DateTime contactsRetriveDat = Convert.ToDateTime(contactsRetriveDate);
if (contactsRetriveDate == "" || toDate.CompareTo(contactsRetriveDat)==0)
{
MessageBox.SHow("");
}
Related
I am trying to filter through things by date. I have 2 DateTimePicker called FromDate and ToDate. I have an array and within one of the array (str[10]) is a date, I tried converting the string into a datetime format but I still get the error:
System.FormatException: 'String was not recognized as a valid DateTime.'
The string within str[10]:
str[10] = "9/22/2017 18:24";
My current code:
string[] date = str[10].Split(' ');
DateTime dateSpec = DateTime.ParseExact(date[0], "MM/dd/yyyy", CultureInfo.CurrentCulture);
if (dateSpec >= FromDate.Value && dateSpec <= ToDate.Value)
{
//Do Something
}
I am not so sure what to do as most forums suggest more or less the same thing. I'm not sure where the error is. I checked the array and the string does not have any spaces as well, thinking that it may have been the reason as to why there was an error
The MM in "MM/dd/yyyy" means the month component will be padded with a 0, if necessary, to make it two digits long. Your input, "9/22/2017", uses only a single-digit month and so doesn't match that format. If you change the format to "M/dd/yyyy" it parses successfully.
Also, you don't need to truncate the time portion yourself; if the time format is consistent (HH : mm) then just parse it and use the Date property to get a DateTime for midnight of the same day...
DateTime dateSpec = DateTime.ParseExact(str[10], "M/dd/yyyy HH:mm", CultureInfo.CurrentCulture);
if (dateSpec.Date >= FromDate.Value && dateSpec.Date <= ToDate.Value)
{
//Do Something
}
Depending on how str is populated (e.g. user input) also consider using DateTime.TryParseExact(), which returns false upon failure rather than throwing a FormatException...
if (DateTime.TryParseExact(str[10], "M/dd/yyyy HH:mm", CultureInfo.CurrentCulture, DateTimeStyles.None, out DateTime dateSpec))
{
// Handle parsing success
if (dateSpec.Date >= FromDate.Value && dateSpec.Date <= ToDate.Value)
{
//Do Something
}
}
else
{
// Handle parsing failure
}
dateSpec is declared at the point it is passed as an out parameter, which is possible since C# 7.0.
I managed to get it working by adding this block of code from another coder's suggestion on another platform
string[] formats = { "M/d/yyyy HH:mm", "M/dd/yyyy HH:mm", "MM/d/yyyy HH:mm", "MM/dd/yyyy HH:mm" };
DateTime dateSpec = DateTime.Now;
if (DateTime.TryParseExact(str[10].ToString(), formats, System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dateSpec))
{
if (dateSpec.Date >= FromDate.Value.Date && dateSpec.Date <= ToDate.Value.Date)
{
//Do Something
}
}
else
{
MessageBox.Show("Error");
}
I have DataGridView where i am showing all details of upcoming movies
Now from this i have to give discount to movies that are in weekend. i am getting date from datagridview
string date = dataGridView1.CurrentRow.Cells["Date"].Value.ToString();
Now i have to convert this date to dayofweek so i can compare day to dayof week by
date == (DayOfWeek.Saturday || DayOfWeek.Sunday)
I tried to find dayofweek by
DateTime dateValue = new DateTime(date);
Console.WriteLine(dateValue.ToString("ddd"));
This code is giving me this error
The best overloaded method match for 'System.DateTime.DateTime(long)' has some invalid arguments
Since it's string, you can parse it to DateTime and check it's DayOfWeek property like;
var dateValue = DateTime.ParseExact(date, "M/d/yyyy", CultureInfo.InvariantCulture);
and
if(dateValue.DayOfWeek == DayOfWeek.Saturday || dateValue.DayOfWeek == DayOfWeek.Sunday)
I honestly don't understand why you use ddd specifier since it represents the abbreviated name and since it uses your CurrentCulture settings, it may not even generate theirs English names.
After your comment, looks like your string has time part also, you just change the format part like;
var dateValue = DateTime.ParseExact(date, "M/d/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture);
var date = "3/2/2016";
var dayOfWeek = DateTime.Parse(date).DayOfWeek;
How can I convert a system date format (like 3/18/2014) to the format readable in DateTime?
I wanted to get the total days from two dates, which will come from two TextBoxes.
I have tried this syntax:
DateTime tempDateBorrowed = DateTime.Parse(txtDateBorrowed.Text);
DateTime tempReturnDate = DateTime.Parse(txtReturnDate.Text);
TimeSpan span = DateTime.Today - tempDateBorrowed;
rf.txtDaysBorrowed.Text = span.ToString();
But tempDateBorrowed always returns the minimum date for a DateTime varibale. I think this is because DateTime does not properly parse my system date format. As a consequence, it incorrectly displays the number of days. For example, if I try to enter 3/17/2014 and 3/18/2014 respectively, I always get -365241 days instead of 1.
Edit: I wanted my locale to be non-specific so I did not set a specific locale for my date format. (My system format by the way is en-US)
Try DateTime.ParseExact method instead.
See following sample code (I've used strings instead of TextBoxes since I used a Console app to write this code). Hope this helps.
class Program
{
static void Main(string[] args)
{
string txtDateBorrowed = "3/17/2014";
string txtReturnDate = "3/18/2014";
string txtDaysBorrowed = string.Empty;
DateTime tempDateBorrowed = DateTime.ParseExact(txtDateBorrowed, "M/d/yyyy", null);
DateTime tempReturnDate = DateTime.ParseExact(txtReturnDate, "M/d/yyyy", null);
TimeSpan span = DateTime.Today - tempDateBorrowed;
txtDaysBorrowed = span.ToString();
}
}
ToString is not Days
TimeSpan.TotalDays Property
You can try specifying the format of the datetime in the textboxes like this
DateTime tempDateBorrowed = DateTime.ParseExact(txtDateBorrowed.Text.Trim(), "M/d/yyyy", CultureInfo.InvariantCulture);
DateTime tempReturnDate = DateTime.ParseExact(txtReturnDate.Text.Trim(), "M/d/yyyy", CultureInfo.InvariantCulture);
Also you may have to check if the values from the textboxes are valid.
My first thought is to just replace the TextBox controls with a DateTimePicker or equivalent, depending on what platform you're developing on. Converting strings to dates or vice-versa is more of a pain than it seems at first.
Or you could try using DateTime.ParseExact instead, to specify the exact expected format:
DateTime tempDateBorrowed =
DateTime.ParseExact("3/17/2014", "M/dd/yyyy", CultureInfo.InvariantCulture);
Or you could specify a specific culture in the call to DateTime.Parse:
var tempDateBorrowed = DateTime.Parse("17/3/2014", new CultureInfo("en-gb"));
var tempDateBorrowed = DateTime.Parse("3/17/2014", new CultureInfo("en-us"));
try formatting your date to iso 8601 or something like that before parsing it with DateTime.Parse.
2014-03-17T00:00:00 should work with DateTime.Parse. ("yyyy-MM-ddTHH:mm:ssZ")
Try this:
if(DateTime.TryParseExact(txtDateBorrowed.Text, "M/d/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out tempDateBorrowed))
{
TimeSpan span = DateTime.Today - tempDateBorrowed;
}
I'm working on formatting datetime's to display on a graph, and its working great so far. I have the format string:
M/dd/yyyy HH:mm:ss
and it prints as I'd like it to except the following: I want to completely hide the HH:mm:ss if the time is midnight.
Is it possible to do without a custom iformatprovider?
Thanks!
DateTime time = DateTime.Now;
string txt = time.ToString(time == time.Date ? "M/dd/yyyy" : "M/dd/yyyy HH:mm:ss");
DateTime time = DateTime.Now;
string format = "";
if (time.Hour == 0)
{
format = "M/dd/yyyy";
}
else
{
format = "M/dd/yyyy HH:mm:ss";
}
A culture-independent version of the solution proposed by #JDunkerley would be:
DateTime time = DateTime.Now;
string txt = time.ToString(time == time.Date ? "d" : "g");
More about standard date and time format strings here.
The proposed solution is not a very good one because it does not take into account user's localized time format, and simply assumes US English.
Here's how it should've been done:
public static string formatDateTimeWithTimeIfNotMidnight(DateTime dt)
{
//RETURN:
// = String for 'dt' that will have time only if it's not midnight
if (dt != dt.Date)
{
//Use time
return dt.ToString();
}
else
{
//Only date
return dt.ToShortDateString();
}
}
I want today's date in mm/dd/yyyy format from a DateTime variable. How to get it?
I need to check this with some date variable so it must be also in date variable format?plz help
Ex: i need to get today date in mm/dd/yyyy format and i already date which is datetime datatype in mm/dd/yyyy format and i have to compare them
You should use DateTime.Today:
DateTime today = DateTime.Today; // As DateTime
string s_today = today.ToString("MM/dd/yyyy"); // As String
Edit: You edited your post to add another question, so here comes my edit to supply at least some sort of answer.
Update While you can use DateTime.Compare() you should use plain comparisson:
if(today < otherdate)
{
// Do something.
}
Alternatively, you can use DateTime-variables to check against other DateTime-variables using the DateTime.Compare() method. Both otpions will work and it comes down to preference and what you want to do with the result.
int result = DateTime.Compare(today, otherdate);
if(result < 0)
MessageBox.Show("Today is earlier than the 'otherdate'");
elseif(result > 0)
MessageBox.Show("Today is later than the 'other date'");
else
MessageBox.Show("Dates are equal...");
string datestring = DateTime.Now.ToString("MM/dd/yyyy");
MSDN say: Custom Date and Time Format Strings
To convert DateTime variable to string in the specified format:
DateTime d = ...;
string s = d.ToString("MM/dd/yyyy");
If you want to compare only date part of DateTime, not time part:
DateTime d1 = DateTime.Parse("10/10/2011");
DateTime d2 = DateTime.Parse("01/01/2011");
if (d1.Date > d2.Date)
{
// do the stuff
}
DateTime.Now.ToString("MM/dd/yyyy");
DateTime.Today.ToString("MM/dd/yyyy");
DateTime.Parse is what you are looking for...