Split string (birthday) to get day, month, year - c#

In my database, date is stored as dd/mm/yyyy. When I retrieve it I want to split the date in string day, string month and string year respectively. How should I go about doing it? "/" will be the delimiter is that right?

You need can use DateTime.ParseExact with format "dd/MM/yyyy": (Where myString is the birthday from the database.)
string myString = "01/02/2015"; // From Database
DateTime birthday = DateTime.ParseExact(myString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
int year = birthday.Year;
int month = birthday.Month;
int day = birthday.Day;
You can then use the DateTime object to get the year, month, day, etc.
Using string.Split is an option too, but storing as a DateTime allows you to use many handy methods/properties it contains, but you can do it using string.Split as so:
string[] birthday = myString.Split('/');
int year, month, day;
int.TryParse(birthday[0], out day);
int.TryParse(birthday[1], out month);
int.TryParse(birthday[2], out year);

If you get birthDate from database as string, you can use split function to split that string into array like:
string birthDate = "2015/02/01";
var split = birthDate.Split('/');
If you get birthDate from database as datetime, you can extract date parts from it like:
DateTime birthDate = DateTime.Now.Date;
var year = birthDate.Year;
var month = birthDate.Month;
var day = birthDate.Day;

Related

How to convert informal string value to Date time in c#

All of my friend.
I want to convert informal string to dateTime in c#. Here my string value is "01042016".How can convert? can i need another step to change DateTime.
This is my code:
string FinancialYear = "01042016-31032017";
string[] splitDate = FinancialYear.Split('-');
DateTime startDate = Convert.ToDateTime(splitDate[0].ToString(),"dd/MM/yyyy"));
As we can see that the input date will be in the format ddMMyyyy so here the best option for converting the input to DateTime object is DateTime.TryParseExact the code for this will be :
string FinancialYear = "01042016-31032017";
string[] splitDate = FinancialYear.Split('-');
DateTime startDate ;
if(DateTime.TryParseExact(splitDate[0],"ddMMyyyy",CultureInfo.InvariantCulture,DateTimeStyles.None,out startDate))
{
// Proceed with the startDate it will have the required date
}
else
// Show failure message
This will create an Enumerable where index 0 is the first date and index 1 is the second date.
string FinancialYear = "01042016-31032017";
var dateRange = FinancialYear.Split('-')
.Select(d => DateTime.ParseExact(d, "ddMMyyyy", CultureInfo.InvariantCulture);
If you are not sure of the format your best bet is using DateTime.Parse() or DateTime.TryParse()
You are not 100% guaranteed that the date will be parsed correctly, especially in cases where the day and month numbers could be in the wrong order.
It is best to specify a required date format if you can so you can be sure the date was parsed correctly.
if you string is in static format, you can convert it by reconvert it to valid string format first such as
string validstring = splitDate[0].ToString().Substring(4,4)+"-"+splitDate[0].ToString().Substring(2,2) +"-"+ splitDate[0].ToString().Substring(0,2);
DateTime startDate = Convert.ToDateTime(validstring,"dd/MM/yyyy"));

How to convert a value from a drop down list into a date type?

I have a three Drop down lists , Day , Month, and year , after I put them into a string how do I convert them into a Date Time, knowing that I'll store this date in a database`
string DOBDay = DDLDay.SelectedValue;
string DOBMonth = DDLMonth.SelectedValue;
string DOBYear = DDLYear.SelectedValue;
string date = DOBDay + DOBMonth + DOBYear;
You can simply do this
Date myDate = new Date(Convert.ToInt32(DDLYear.SelectedValue),
Convert.ToInt32(DDLMonth.SelectedValue),
Convert.ToInt32(DDLDay.SelectedValue));

Converting an inputted string into a date

I have been trying to get a date conversion to wrok to convert from a string to a date I have looked at msdn and some other stack o questions but multiple ways have not worked. I am making a console app and it needs a valid date to check other dates. below is my current attempt.
string StartDate, EndDate;
Console.WriteLine("Input Start date");
StartDate = Console.ReadLine();
StartDate = DateTime.Parse(StartDate);
I currently set the variable StartDate and then set it a value depending on what the user enters and then it should change this to a date using the Parse
you are trying to assign the DateTime value to string StartDate, which is wrong. So change it like below:
string StartDate, EndDate;
DateTime date;
Console.WriteLine("Input Start date");
StartDate = Console.ReadLine();
date = DateTime.Parse(StartDate);
A string is not a DateTime and a DateTime not a String. So you might be able to parse a string to a date but you cannot use the string variable for the DateTime and vice-versa. You need two variables:
string startDateInput = Console.ReadLine();
DateTime startDate = DateTime.Parse( startDateInput );
Since this could fail if the input string is not a valid date you should use TryParse:
DateTime startDate;
bool validDate = DateTime.TryParse(startDateInput, out startDate);
if(validDate)
Console.Write("Valid date: " + startDate.ToLongDateString());
Try using Convert.ToDateTime();
Example:
string date = "01/08/2008";
DateTime dt = Convert.ToDateTime(date);
Use DateTime.TryParse()
Converts the specified string representation of a date and time to its
DateTime equivalent and returns a value that indicates whether the
conversion succeeded.
DateTime date;
if (!DateTime.TryParse("DateString", out date))
{
MessageBox.Show("Invalid string!");
}
You need to specify the Date Format.
Try This: Example format MM-dd-yyyy
Console.WriteLine("Input Start date Format -> MM-dd-yyyy");
string StartDate = Console.ReadLine();
DateTime YourDate = DateTime.ParseExact(StartDate,"MM-dd-yyyy",
System.Globalization.CultureInfo.InvariantCulture);

String To DateFormat Conversion

Is there any way I don't have to specify the number of digits in day/month/year?
For e.g 1/2/1991
I want a method which satisfies both 1/2/1991,11/3/1990,12/12/1991
I don't know how many digits will be there in either month, year, or days.
My code is
string copy = splittedData[0] + splittedData[1] + splittedData[2];//date+month+year
DateTime datetime = DateTime.ParseExact(copy, "ddMMyyyy", CultureInfo.InvariantCulture);
DateTime dateAndTime = datetime;
The problem is the number of digits in splitted data array are not known to me and thus the above format "ddMMyyyy" give me exception on some cases.
Since you already have the day month and year then just create a date with the three of them like so;
DateTime date = new DateTime(year, month, day);
No parsing is necessary. You already have all the fields you want to create the date, and you dont need to put it into a special format to create a date.
If you are not sure the if the input is valid, then wrap the creation in a try/catch block to catch an ArgumentOutOfRangeException should it should occur.
Since you updated your question with the code you have, you can concatenate date components with a separator like:
string copy = splittedData[0] + "/" + splittedData[1] + "/" + splittedData[2];
Later you can do:
DateTime dt = DateTime.ParseExact(copy, "d/M/yyyy", CultureInfo.InvariantCulture);
I used the format "d/M/yyyy" with single d and M which would account for both single/double digit day/month.
So it will work for dates like:
01/01/2013
1/01/2013
22/09/2013
02/9/2013
DateTime.ParseExact is specifically intended to not allow what you are asking for. DateTime.Parse will allow it, though.
You say you have the 3 parts as separate strings -- if you insert the /'s and parse, it should succeed (InvariantCulture expects the order month-day-year):
string datetimeString = string.Join("/", new[] {month, day, year});
DateTime datetime = DateTime.Parse(datetimeString, CultureInfo.InvariantCulture);
Or you could convert them to integers and construct a DateTime directly:
DateTime datetime = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), Convert.ToInt32(day));
What #n00b said. You've already got the individual components of the date: why are you globbing them back together just so you can call DateTime parsing routines? Just do something like this:
private static DateTime StringToDateTime( string year , string month , string day )
{
int yyyy = int.Parse(year) ;
int mm = int.Parse(month) ;
int dd = int.Parse(day) ;
DateTime dt = new DateTime(yyyy,mm,dd) ;
return dt ;
}
As an added bonus, The above code will probably run faster than DateTime.Parse() or DateTime.ParseExact().

Get the system date and split day, month and year

My system date format is dd-MM-yyyy(20-10-2012) and I'm getting the date and using separator to split the date, month and year. I need to convert date format (dd/MM/yyyy) whether the formats returns at any date format.
string sDate = string.Empty;
DateTime _date = DateTime.Now;
int count = 0;
string format = "dd-MM-yyyy";
sDate = dateFormat.ToString(format);
string[] Words = sDate.Split(new char[] { '-' });
foreach (string Word in Words)
{
count += 1;
if (count == 1) { Day = Word; }
if (count == 2) { Month = Word; }
if (count == 3) { Year = Word; }
}
Here is what you are looking for:
String sDate = DateTime.Now.ToString();
DateTime datevalue = (Convert.ToDateTime(sDate.ToString()));
String dy = datevalue.Day.ToString();
String mn = datevalue.Month.ToString();
String yy = datevalue.Year.ToString();
OR
Alternatively, you can use split function to split string date into day, month and year here.
Hope, it will helps you... Cheers. !!
You can do like follow:
String date = DateTime.Now.Date.ToString();
String Month = DateTime.Now.Month.ToString();
String Year = DateTime.Now.Year.ToString();
On the place of datetime you can use your column..
You can split date month year from current date as follows:
DateTime todaysDate = DateTime.Now.Date;
Day:
int day = todaysDate.Day;
Month:
int month = todaysDate.Month;
Year:
int year = todaysDate.Year;
You should use DateTime.TryParseExcact if you know the format, or if not and want to use the system settings DateTime.TryParse. And to print the date,DateTime.ToString with the right format in the argument. To get the year, month or day you have DateTime.Year, DateTime.Month or DateTime.Day.
See DateTime Structures in MSDN for additional references.
Without opening an IDE to check my brain works properly for syntax at this time of day...
If you simply want the date in a particular format you can use DateTime's .ToString(string format). There are a number of examples of standard and custom formatting strings if you follow that link.
So
DateTime _date = DateTime.Now;
var _dateString = _date.ToString("dd/MM/yyyy");
would give you the date as a string in the format you request.
TL&DR; The DateTime Object in C# has the ability to extract the string information using the ToString() function with the correct format string. (ie: "yyyy-mm-dd");
string onlyDateWithoutTimeStamp = lastDate.ToString("yyyy-MM-dd");

Categories

Resources