How to find dayofweek from date stored in string? - c#

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;

Related

DateTime string format in c#

I have a project that contain 3 string variables.
DateFormatStr is the format string I need to use to output dates.
DateFormatFrom is the start date a request will apply from
FilloutDateTo is the end date the request will apply to.
The problem is that I don't want to manually specify the dates. As you can see in my example below (a working example), I need to specify the dates, but is there a way to make it that the from date has time 00:00:00 and the end date has time 23:59:59?
string DateFormatStr = "MM/dd/yy hh:mm:ss tt";
string DateFormatFrom = "12/04/14 00:00:00";
string FilloutDateTo = "12/04/14 23:59:59";
So I would like to the system time to recognize the from date and the start date respecting the formatStr variable.
Thanks
If I understand correctly, you can use DateTime.Today property like;
var dt1 = DateTime.Today;
var dt2 = DateTime.Today.AddDays(1).AddSeconds(-1);
and use DateTime.ToString() to format them like;
var DateFormatFrom = dt1.ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
var FilloutDateTo = dt2.ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Results will be;
12/04/2014 00:00:00
12/04/2014 23:59:59
You used hh format specifier but it is for 12-hour clock. Use HH format specifier instead which is for 24-hour clock. And since your result strings doesn't have any AM/PM designator, you don't need to use tt format specifier.
In C# 6.0 you can use string interpolation in order to display formatted dates.
DateTime startOfDay = DateTime.Today;
DateTime endOfDay = DateTime.Today.AddDays(1).AddTicks(-1);
string dateFormatFrom = $"{startOfDay: MM/dd/yy hh:mm:ss tt}";
string filloutDateTo = $"{endOfDay: MM/dd/yy hh:mm:ss tt}";
string idate = "01/11/2019 19:00:00";
DateTime odate = Convert.ToDateTime(idate);
DateTime sdate1 = DateTime.Parse(idate);
string outDate1 = String.Format("{0}/{1}/{2}", sdate1.Day, sdate1.Month,sdate1.Year);
Console.WriteLine(outDate1);

Converting string to date in another culture

I am trying to convert a string (which represents date in invariantCulture) to dateTime in given culture. The problem is that when the date is converted to German culture, the day becomes month and month becomes day.
What is wrong with below code or am i missing something ?
var day = 11; var month = 12; var year = 2014;
var someDate = new DateTime(year, month, day);
var theDay = someDate.Day;//11 ok as expected
var theMonth = someDate.Month; //12 ok as expected
var dateString = someDate.ToString(CultureInfo.InvariantCulture);
var date1 = DateTime.Parse(dateString, CultureInfo.GetCultureInfo("de-De"));
var day1 = date1.Day;//12 this should be 11 ?
var month1 = date1.Month; //11 this should be 12 ?
The second argument to DateTime.Parse is used to tell the parser what format the string is in, not what format you want to convert it to. You are generating an invariant string and then parsing it as a German string which is why your day and month are getting swapped.
If your goal is to get a German string representation of the date, just use var dateString = someDate.ToString(CultureInfo.GetCultureInfo("de-DE")).
I guess de-De culture doesn't have a standard date and time format as MM/dd/yyyy HH:mm:ss.
Since you using DateTime.ToString() method with InvariantCulture, result string will be "G" standard format which is MM/dd/yyyy HH:mm:ss for InvariantCulture.
Because of that, dateString will be 12/11/2014 00:00:00 and de-DE culture doesn't have a standard date and time format MM/dd/yyyy HH:mm:ss but has dd/MM/yyyy HH:mm:ss which is dd.MM.yyyy HH:mm:ss for de-DE culture.
That's why DateTime.Parse method matches pattern which is dd/MM/yyyy HH:mm:ss (since it's DateSeparator is . it should be dd.MM.yyyy HH:mm:ss format).
That's why it parses your 12 as a Day and 11 as a Month.
If you already a DateTime (which you have) just use .ToString() method with your de-DE culture like;
var culture = new CultureInfo("de-De");
var dateString = someDate.ToString(culture);
Remember, a DateTime doesn't have any implicit format or culture. It just have date and time values. String representations of them can have formats.
By the way, you can find all standard date and time patterns your de-DE culture like;
var culture = new CultureInfo("de-De");
foreach (var format in culture.DateTimeFormat.GetAllDateTimePatterns())
{
Console.WriteLine(format);
}
Change the following line and test it again:
var dateString = someDate.ToString(CultureInfo.InvariantCulture);
to:
var dateString = someDate.ToString("O");
or:
var dateString = someDate.ToString("S");
ok, here is what i think what you want to accomplish, not sure if i got you right: you want to read an invariant cultured date string and convert it to a german cultured date string.
but in your example you are trying to parse an invariant cultured date AS a german cultured date. of course that leads to a misinterpretation. try this:
string invariantCultureDateString = "12/11/2014 00:00:00";
var dateTime = DateTime.Parse(invariantCultureDateString, CultureInfo.InvariantCulture);
string germanCultureDateString = dateTime.ToString(CultureInfo.GetCultureInfo("de-De"));
BR

Converting System Date Format to Date Format Acceptable to DateTime in C#

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;
}

DateTime Format Handling

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("");
}

date conversion error

I am developing windows application.
In that i have date in the string format as>> fileDate="15/03/2013"
I want it to be get converted into date format as my database field is datetime.
I used following things for it>>
DateTime dt = DateTime.ParseExact(fileDate, "yyyyy-DD-MM", CultureInfo.InvariantCulture);
DateTime dt = DateTime.Parse(fileDate);
Both of these methods proved failure giving me error>>
String was not recognized as a valid DateTime.
What can be mistake?
Is there another technique to do that?
string fileDate = "15/03/2013";
DateTime dt = DateTime.ParseExact(fileDate, "dd/mm/yyyy", CultureInfo.InvariantCulture);
You have to give the date format according to the date string you have to ParseExact. You can see more on Custom DateTime format - MSDN
Change
"yyyy-MM-dd HH:ss"
To
"dd/MM/yyyy"
Your code would be
DateTime dt = DateTime.ParseExact(fileDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
You should do this:
DateTime dt = DateTime.ParseExact(fileDate, "dd/MM/yyyy",CultureInfo.InvariantCulture);
You must pass in the string for the format ("dd/MM/yyyy") in the same style that you pass in the string fileDate.
u may try with this
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate = dateFormat.parse("ur_dateString")
In your current code you are using format "yyyyy-DD-MM" which is wrong since date part require lower case d not upper case D. , Also for year part you are specifying 5 ys, it should be 4, like yyyy, the order according to your date string should be: "dd/MM/yyyy". To be on the safe side you can even use "d/M/yyyy", which would work for single digit or double digit day/month.
So your code should be:
string fileDate="15/03/2013";
DateTime dt = DateTime.ParseExact(fileDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
You can see more on Custom DateTime format - MSDN
It's because string "15/03/2013" cannot really be parsed as DateTime with format string "yyyy-MM-dd HH:ss".

Categories