Split the date in c# - c#

For Ex
You date enter in the various form in textbox
12/Augest/2010
augest/12/2010
2010/12/Augest
and out put is
three textbox First is day show= 12
textbox second is Months show= augest
textbox third is Year show= 2010

To parse/validate against three expected formats, you can use something like below. Given the pattern, once you know it is valid you could just use string.Split to get the first part; if you need something more elegant you could use TryParseExact for each pattern in turn and extract the desired portion (or re-format it).
string s1 = "12/August/2010",
s2 = "August/12/2010",
s3 = "2010/12/August";
string[] formats = { "dd/MMMM/yyyy", "MMMM/dd/yyyy", "yyyy/dd/MMMM" };
DateTime d1 = DateTime.ParseExact(s1, formats,
CultureInfo.CurrentCulture, DateTimeStyles.None),
d2 = DateTime.ParseExact(s2, formats,
CultureInfo.CurrentCulture, DateTimeStyles.None),
d3 = DateTime.ParseExact(s3, formats,
CultureInfo.CurrentCulture, DateTimeStyles.None);

Use DateTime.Parse(String, IFormatProvider) or DateTime.ParseExact to convert the string into DateTime.
Then you can extract the day, month and year using the corresponding properties.

Use DateTime.Parse(s). See MSDN
Then you can get the individual parts of a DateTime structure.
e.g.
DateTime date = DateTime.Parse("some input date string");
string day = DateTime.Day.ToString();
string month = DateTime.Month.ToString();
string year = DateTime.Year.ToString();

date dt date.Parse(txtBox.text);
txtBox1.Text = dt.Day.ToString();
txtBox2.Text = dt.ToString("MMM");
txtBox3.Text = dt.Year.ToString();
date.Parse might throw depending on the string you give it, but then you can fall back by trying to parse it using a different culture.
Edit: Added an M

Related

C# parse DateTime String to time only

I am new to C# and I have a string like "2021-06-14 19:27:14:979". Now I want to have only the time "19:27:14:979". So do I parse the string to a specific DateTime format and then convert it back to a string or would you parse or cut the string itself?
It is important that I keep the 24h format. I don't want AM or PM.
I haven't found any solution yet. I tried to convert it to DateTime like:
var Time1 = DateTime.ParseExact(time, "yyyy-MM-dd HH:mm:ss:fff");
var Time2 = Time1.ToString("hh:mm:ss:fff");
But then I lost the 24h format.
Your code is almost working, but ParseExact needs two additional arguments and ToString needs upper-case HH for 24h format:
var Time1 = DateTime.ParseExact("2021-06-14 19:27:14:979", "yyyy-MM-dd HH:mm:ss:fff", null, DateTimeStyles.None);
var Time2 = Time1.ToString("HH:mm:ss:fff");
Read: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings#uppercase-hour-h-format-specifier
Instead of passing null as format provider(means current culture) you might want to pass a specifc CultureInfo, for example CultureInfo.CreateSpecificCulture("en-US").
You can just split it at the blank and take the last part like this
var timestamp = "2021-06-14 19:27:14:979";
var timePart = timestamp.Split(' ')[1];
in your case that seems easier than parsing into a DateTime and back into a string.

Can't convert from String to Char

I'm trying to Split this string: 2015-08-14 20:30:00
but the compiler shows this message:
Can't convert from String to Char
This is my code:
string date = reader["date"].ToString().Split("-").ToString();
The variable reader["date"] is an object, so I must convert it into a String. I want to Split the content into three other variable like this:
year: 2015
month: 08
day: 14
What am I doing wrong?
There is no String.Split overload that takes string as a parameter. That's why it looks closest overload which is char[] but there is no implicit conversation between them.
var array = "2015-08-14 20:30:00".Split(new char[]{'-', ' '});
will return
and you can get them with array[0], array[1] and array[2].
Also you can use to parse your string to DateTime instead (which your string is valid one) of splitting it like;
string s = "2015-08-14 20:30:00";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// dt.Year;
// dt.Month;
// dy.Day;
}
But since these properties are int, you will not get leading zeros for your single digit month and days.
In such a case, you can choose to use dd and MM custom date and time format specifiers.
Sometime a different approach should be considered. If your reader field datatype is date or datetime then using the correct datatype is the correct way to handle this info. A DateTime has already all you need.
DateTime dt = Convert.ToDateTime(reader["date"]);
int year = dt.Year;
int month = dt.Month;
int day = dt.Day;
As String.Split reaturns an array of strings you need date to be the same. So simply write
string[] date = Convert.ToString(reader["date"]).Split("-");

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

Remove '0' (Number) from DateTime Month and Day (String)

Can anybody tell me the best approach or solution on how I would do the following?
I have a DateTime (as String) in following format:
string test = "21.12.2013";
How could I now remove all zero's from the month and day but still 'keep' the DateTime Logic:
//Example 1
string input = "06.10.2013" // 6th October
string output = "6.10.2013" //only remove '0' from the day
//Example 2
string input = "01.09.2012" // 1st September
string output = "1.9.2012" //remove from month and day
//Example 3
string input = "20.10.2011" // 20th October
string output = "20.10.2011" //should (must) stay!
I can also parse to DateTime if that would be make it easier but yeah I hope you got my idea...
Any help appreciated!
Parsing your string into DateTime and getting it back to string using ToString with desired patter seems to be the easiest way to go:
public static string GetRidOfZeros(string input)
{
var dt = DateTime.ParseExact(input, "dd.MM.yyyy", CultureInfo.InvariantCulture);
return dt.ToString("d.M.yyyy", CultureInfo.InvariantCulture);
}
Little testing, with your sample data:
var inputs = new List<string> { "06.10.2013", "01.09.2012", "20.10.2011" };
var outputs = new List<string> { "6.10.2013", "1.9.2012","20.10.2011" };
if(outputs.SequenceEqual(inputs.Select(d => GetRidOfZeros(d))))
Console.WriteLine("Output is OK");
else
Console.WriteLine("Collections does not match.");
Prints Output is OK.
DateTime.Parse(input).ToString("d.M.yyyy")
As you said, parsing to DateTime first would probably make things easier, since then you can just use:
myDateTime.ToString("d.M.yyyy");
When you parse it you can use ToString to format it any way you like:
var date = "06.10.2013";
DateTime parsed = DateTime.ParseExact(date, "dd.MM.yyyy", CultureInfo.InvariantCulture);
var noZerosHere = parsed.ToString("d.MM.yyyy");
A decent "catch-all" method (that will work not just on DateTime but ANY kind of string) would be to split the string up, take out leading zeroes and then put the pieces back together again.
string input = "01.09.2012";
string[] values = input.Split(".");
string[] modifiedValues = values.Select(x => x.TrimStart('0');
string output = String.Join(".", modifiedValues);
You can adjust the delimiters for different representations of DateTime, e.g. those that use slashes (01/09/2012) or are written in a different order.

How to convert a date of integers to a formated date string (i.e. 2012009 to 2/01/2009)

Any ideas?
I can't come up with any.
I have a list of dates I'm loading in from a csv file and they are saved as all integers, or rather a string of integers (i.e. Jan 1, 2009 = 1012009)
Any ideas on how to turn 1012009 into 1/01/2009?
Thanks!
Since the date is stored as a string, you may want to use ParseExact:
DateTime date = DateTime.ParseExact("28012009", "dMMyyyy", null);
ParseExact will throw an exception if the format doesn't match. It has other overloads, where you can specify more than a single possible format, if that is required. Note that here provider is null, which uses the current culture.
Depending on style you may wish to use TryParseExact.
int date = 1012009;
var month = date / 1000000;
var day = (date / 10000) % 100;
var year = date % 10000;
var formatted = new DateTime(year, month, day).ToString();
This assumes month-day-year; if the numbers are day-month-year, I’m sure you’ll be able to swap the month and day variables to accommodate that.
If you want to customise the date format, you can do so as described in:
Standard Date and Time Format Strings
Custom Date and Time Format Strings
Let 10102009 be dateInt.
string dateString = dateInt.ToString();
int l = dateString.Length;
dateString = dateString.Insert(l-3,"/");
dateString = dateString.Insert(l-6,"/");
You should now have 1/01/2009 in dateString.. You can also try the ParseExact function..

Categories