Parsing a Date Range in C# - ASP.NET - c#

Given say 11/13/2008 - 12/11/2008 as the value posted back in TextBox, what would be the best way to parse out the start and end date using C#?
I know I could use:
DateTime startDate = Convert.ToDateTime(TextBoxDateRange.Text.Substring(0, 10));
DateTime endDate = Convert.ToDateTime(TextBoxDateRange.Text.Substring(13, 10));
Is there a better way?

var dates = TextBoxDateRange.Text.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
var startDate = DateTime.Parse(dates[0], CultureInfo.CurrentCulture);
var endDate = DateTime.Parse(dates[1], CultureInfo.CurrentCulture);

Instead of Convert.ToDateTime, it could be worth to use DateTime.Parse and explicitely put in the Culture you desire. If I try that example with any European Culture, i get an Error because 11/13/2008 points to the 11th Day in the 13th Month of 2008...
CultureInfo ci = new CultureInfo("en-us");
var startDate = DateTime.Parse(components[0], ci);

Related

Parse string to DateType ASP.NET C# exception - The string was not recognized as a valid DateTime

So I have a date which is in this format. My goal is to add 7 days to this string startdate and post it into a database as a string. However, I have to convert it to datetime to allow me to add days to it. I am reading startdate from a database but this is what it looks like.
string startdate = "10-03-2018 03:15PM";
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime starttime2 = DateTime.ParseExact(startdate, "MM/dd/yyyy HH:mm tt", culture);
// It is breaking on the above line with the error - The string was not recognized as a valid DateTime.
DateTime endtime2 = starttime2.AddDays(+7);
Anyone able to help me solve this issue? I am new to C# and would appreciate any help at all..
Thank you
You have specified wrong format actually. You should be specifying the following format:
"dd-MM-yyyy hh:mmtt"
as your date is in format :
"10-03-2018 03:15PM"
Assuming that the first number us for day and second is for month, otherwise you can swap those.
You can see more details on the usage of ParseExact here.
Try this:
string startdate = "10-03-2018 03:15PM";
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime starttime2 = DateTime.ParseExact(startdate, "dd-MM-yyyy hh:mmtt", culture);
no space between mm and tt. also this is 12 hours format so hh
I think this will help you
public static DateTime AddDaysToMyDate(string date)
{
return DateTime.ParseExact(date, "dd-MM-yyyy hh:mmtt", new CultureInfo("en-US", true)).AddDays(7);
}
Use it as
DateTime newDateTime = AddDaysToMyDate("10-03-2018 03:15PM");

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

C# DateTime.ParseExact determining year prefix

I have a requirement regarding the parsing of date strings of the form "dd/MM/yy" such that if the year is deemed greater than 30 years from the current year then it would prefix the year with 19. In the other instance it is prefixed with 20.
Examples:
01/01/50 -> 01/01/1950
01/01/41 -> 01/01/2041
I'm not sure how DateTime.ParseExact decides what prefix it should use or how I can force it one way or the other (it does appear to make a sane assumption as 01/01/12 -> 01/01/2012, I just don't know how to dictate the point at which it will switch).
Use the Calendar.TwoDigitYearMax property.
Gets or sets the last year of a 100-year range that can be represented
by a 2-digit year.
In your case, something like this would work:
// Setup
var cultureInfo = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
var calendar = cultureInfo.Calendar;
calendar.TwoDigitYearMax = DateTime.Now.Year + 30;
cultureInfo.DateTimeFormat.Calendar = calendar;
// Parse
var _1950 = DateTime.ParseExact("01/01/50", "dd/MM/yy", cultureInfo);
var _2041 = DateTime.ParseExact("01/01/41", "dd/MM/yy", cultureInfo);
I do not think that ParseExact can do your job, so here my version with conditional blocks but works.
Try This:
DateTime currentDate = DateTime.Now;
String strDate = "01/01/41";
DateTime userDate=DateTime.ParseExact(strDate, "dd/MM/yy", System.Globalization.CultureInfo.InvariantCulture);
currentDate=currentDate.AddYears(30);
if ((userDate.Year%100) > (currentDate.Year%100))
{
strDate = strDate.Insert(6, "19");
}
else
{
strDate = strDate.Insert(6, "20");
}
DateTime newUserDate = DateTime.ParseExact(strDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);

Join date and time strings into a DateTime

Given two strings with the following values:
31/05/2013 0:00:00
21:22
What's the most efficient way to join them into a DateTime data type to get:
31/05/2013 21:22
The time portion of the first string "0:00:00" is ignored, in favor of using the "time" from the second string.
Use a TimeSpan object and DateTime.Add(yourTimeSpan); e.g.
DateTime dt = new DateTime(2013,05,31);
var dts = dt.Add(new TimeSpan(0, 21, 22, 0, 0));
Extending the answer a bit, you can parse the date and time first, e.g.
DateTime dt = DateTime.Parse("05/31/2013 0:00:00");
TimeSpan ts = TimeSpan.Parse("21:22");
var dts = dt.Add(ts);
...keep in mind, I am not checking for bad date/time values. If you're unsure if the values are real dates/times, use DateTime.TryParse and handle appropriately.
As #George said, parse the first value as a DateTime and then another one as TimeSpan and then add the TimeSpan to first parsed value.
Another option is getting the substring of first 10 charachters of first value and concat it with a space with second value and parse it as DateTime.
Say that the first string is called one and the second one is called two, just do this:
DateTime result = DateTime.Parse(one).Date + DateTime.Parse(two).TimeOfDay;
string strDate = "31/05/2013 0:00";
string strTime = "21:22";
strDate = strDate.Replace("0:00", strTime);
DateTime date = Convert.ToDateTime(strDate);
If you are really dealing with only strings, then:
string strDate = "31/05/2013 0:00:00";
string strTime = "21:22";
string strDateTime = strDate.Split(' ')[0] + " " + strTime;
If you can safely assume you are getting 2 digit month and day, a 4 digit year, and a space after the date:
var date = "31/05/2013 0:00:00";
var time = "21:22";
var dateTime = DateTime.Parse(date.Substring(0,11) + time);
If the assumptions about the input format aren't solid you could use a regex to extract the date instead of Substring.
If you're starting out with just strings, you can just do this:
var dateString = "31/05/2013 00:00";
var timeString = "21:22";
var dateTimeString = dateString.Substring(0, 11) + timeString;
var output = DateTime.ParseExact(dateTimeString, "dd/MM/yyyy HH:mm", null);
Assuming you know for sure this format won't change (a dangerous assumption, to be sure), this will work. Otherwise, you'd have to parse the date and time strings separately and use conventional date manipulation as others suggested. For example:
var ci = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB");
var dateString = "31/05/2013 00:00";
var timeString = "21:22";
var output = DateTime.Parse(dateString, ci) + TimeSpan.Parse(timeString, ci);
DateTime date = DateTime.ParseExact("31/05/2013 0:00:00", "dd/MM/yyyy h:mm:ss", CultureInfo.InvariantCulture);
TimeSpan span = TimeSpan.ParseExact("21:22", "t", CultureInfo.InvariantCulture);
DateTime result = date + span;

How to get DayOfWeek in a local CultureInfo?

DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
string day = dt.DayOfWeek.ToString();
day = day.Substring(0, 1).ToUpper();
MessageBox.Show(day); // result is "F"
How could I get the result in a local language (CultureInfo), for example - France and where can I find a list of languages references for this purpose ?
Assuming you've already got the CultureInfo, you can use:
string dayName = dateTime.ToString("dddd", culture);
You'd then need to take the first character of it yourself - there's no custom date/time format for just that. You could use ddd for the abbreviated day name, but that's typically three characters, not one.
As for a list of cultures - you can use CultureInfo.GetCultures. It will vary by platform, and could vary over time and even by version of .NET, too.
As an aside, this code isn't ideal:
DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
If you happen to call it just before midnight at the end of a year, you could get the "old" year but then January as the month. You should evaluate DateTime.Now (or DateTime.Today) once, and then use the same value twice:
DateTime today = DateTime.Today;
DateTime startOfMonth = new DateTime(today.Year, today.Month, 1);
Straight from the MSDN: MSDN on DateTime with CultureInfo
DateTime dt = DateTime.Now;
// Sets the CurrentCulture property to U.S. English.
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
// Displays dt, formatted using the ShortDatePattern
// and the CurrentThread.CurrentCulture.
Console.WriteLine(dt.ToString("d"));
Try dt.ToString("dddd") and then manipulate that string if necessary. See Custom Date and Time Format Strings.
DateTime dateValue = new DateTime(2008, 6, 11);
Console.WriteLine(dateValue.ToString("ddd",
new CultureInfo("fr-FR")));
it is as simple as this:
var culture = new CultureInfo("da-DK");
var datestring =datetime.ToString("dd MMMMM yyyy kl. hh:mm",culture)

Categories