String To DateFormat Conversion - c#

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().

Related

Parse date string with single digit day e.g. 1-11-2017 as well as 12-11-2017

So I have a date String coming in with the short date of today.
For Example "1-11-2017"
//Here i convert the HttpCookie to a String
string DateView = Convert.ToString(CurrDay.Value);
//Here i convert the String to DateTime
DateTime myDate = DateTime.ParseExact(DateView, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
After running the code I get the error:
FormatExeption was unhandled by user code
An exception of type 'System.FormatException' occurred in
mscorlib.dll but was not handled in user code
Additional information: String was not recognized as a valid DateTime.
1-11-2017 is not in the format of dd-MM-yyyy, specifically the first part. Use d-M-yyyy instead which will use one digit day and month when the value is below 10 (ie. no 0 padding).
Test:
DateTime myDate = DateTime.ParseExact("1-11-2017", "d-M-yyyy", System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(myDate.ToString());
If you do not know if there will be 0 padding you can pass an array of acceptable formats, the parser will try each one in order they appear in the array.
DateTime myDate = DateTime.ParseExact("1-11-2017", new string[]{"d-M-yyyy", "dd-MM-yyyy"}, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
Fiddle
The Date format ddstands for The day of the month, from 01 through 31. You either supply it as 01-11-2017 or change your formatter to d-MM-yyyy.
Here's a reference to Custom Date and Time Format Strings
I solved this using yyyy-MM-dd instead of dd-MM-yyyy
(and later converting it to normal dates)
Becouse the var always was the day of today the day can be 1 and 2 digits
CurrDay.Value = DateTime.Now.ToString("yyyy-MM-dd" );
// Convert String to DateTime
dateFrom = DateTime.ParseExact(CurrDay.Value.ToString(), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
The comments below helped me find this solution,
Thanks to everyone!
Pass the value like below,
string DateView = Convert.ToString("01-11-2017");
DateTime myDate = DateTime.ParseExact(DateView, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
It's because ParseExact means you pass the format and the method expects the same date format to be passed as string, that's why you need to pass d-MM-yyyy instead of dd-MM-yyyy.
I you're not sure if the passed string will be with one digit or two then do the following:
string[] digits = DateView.split('-');
DateTime dateTime = new DateTime(digits[2], digits[1], digits[0]);
You even can split using / instead, but you need to make sure the first digit is a day and the second is month, and so on.
My advice is pass ticks instead of string of datetime:
DateTime date = new DateTime(numberOfTicks);
string valueAsStr = date.ToString("dd-mm-yyyy");

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

removing time from datetime in c# and retaining datetime format

How can I remove time from datetime and store the output in datetime format? I do not want to show the time.
Say I have
string d = "2/27/2013 4:18:53 PM"
How can I store the output in a DateTime variable with only the date and not time.
I can use ToShortDateString() but then it return a string and not datetime.
My ultimate goal is to sort the date column chronologically which can only be done if all the entries are in datetime format and not string.
The Date property of the DateTime struct will give you a date but it will always have a time component that represents midnight ("00:00:00"). If you're starting with a string, you might be able to work with something like this:
DateTime d = DateTime.Parse("2/27/2013 4:18:53 PM").Date; // 2/27/2013 12:00:00 AM
Just make sure you perform your comparison on DateTime objects (i.e. omit all usages of ToString()).
Alternatively, you can format your date in the "sortable" time format:
string d = DateTime.Parse("2/27/2013 4:18:53 PM").ToString("s");
or
string d = yourDateTime.ToString("s");
For the above case d would be 2013-02-27T16:18:53. When sorted alphabetically, the strings will be in chronological order.
DateTime dt = DateTime.now(); (To get Any Date)
string datewithMonth= dt.ToString("MMMM dd, yyyy");
string onlyDate = DateTime.Parse(datewithMonth).ToShortDateString();
Here we get result as 1/1/2014. So that we can perform select operation on sql like this:
searchQuery = "select * from YourTableName where ColumnName = ' " + onlyDate + " ' ";
What about removing the time in culture:-
var submissionDateData = DateTime.Now.ToShortDateString();
var submissionDate = DateTime.Parse(submissionDateData, CultureInfo.CreateSpecificCulture("en-GB"));
First line gives 02/11/2015
Second line gives 11/02/2015 12:00:00 AM
Do you have to do a string split on this or is there a way to get rid of the time?
As easy as this:
d.ToString("mm/dd/yyyy");
DateTime date = DateTime.Parse(d);

How can I split a date and time into an array in C#?

I have the following code that splits dd/mm/yy :
var ukDatea = a.split('/');
return (ukDatea[2] + ukDatea[1] + ukDatea[0]) * 1;
How can I change this so that I can use dd/mm/yy hh:MM and then get the hours and minutes into another array called ukTime? My problem is I am not sure how to split the remainder of the time?
There are several ways of doing that:
First split on the space, then split the date part on slash and the time part on colon.
Use a regular expression to extract all the parts.
Use the DateTime.ParseExact method to parse the string into a DateTime value.
First split with var arr = a.Split(" "). You have now dd/mm/yy and hh:MM in a array.
Now use arr[0].Split('/') to get dd mm and yy.
For time use arr[1].Split(':') and you get hh and MM
The DateTime structure is what you're looking for.
From your original a string containing your date, you can create a DateTime structure with:
DateTime MyDateTime;
dateTime = new DateTime();
dateTime = DateTime.ParseExact(a, "yyyy/MM/dd HH:mm",
null);
MyDateTime then contains a date structure.
You can then define ukDatea:
string[] ukDatea = new string[3] { dateTime.Day, dateTime.Month, dateTime.Year };
and
string[] ukTime - new string[2] { dateTime.Hour, dateTime.Minute };

Watin : Get Datetime and perform calculation

I have a textfield that has a date with the format "12/23/2010".Is there away for me to get the number 23 using watin ie get number from textfield;i'm gonna use it like this.
1.Get datetime 12/23/2010 and get number '23'
2.substract 2 from 23 and store it somewhere[ie: 23 - 2 = 21]
3.Insert the new datetime number [ie:12/21/2010 ]
string myDate = browser.TextField(Find.ByName("myTextField")).Value;
DateTime time = = new DateTime();
time2 = time - 2;
browser.TextField(Find.ByName("myTextField")).TypeText(time2);
Is this possible?or should i be looking to another way.Ask the user to insert the data instead.
You should use DateTime.Parse, DateTime.TryParse, DateTime.ParseExact or DateTime.TryParseExact to parse from text to a DateTime.
If a failure to parse indicates a failure in the code somewhere (which is probably the case here, given that it's a test) I suspect DateTime.ParseExact is the most appropriate approach, providing the expected format, culture etc.
if what you want is to subtract 2 days from a date I would do it like this:
DateTime dt = DateTime.Parse(myDate)-TimeSpan.FromDays(2);
//its steps 1,2 & 3 in one easy to read line :)
This is of course if you are sure the string you have IS a valid date. If it might not be, then you should do what the Skeet recommends, which is using first a try parse, checking if the return value is true, and if it is, then do the rest, and if it is not, send an error message.
consider writing
DateTime dt = Convert.ToDateTime(myDate);
DateTime dtNew = new DateTime(dt.Year, dt.Month, dt.Day - 2);
browser.TextField(Find.ByName("myTextField")).TypeText(dtNew.ToShortDateString());
Try getting the value of the date as string
Convert it to datetime and use AddDays we can use negative or positive value
And insert it into textbox
string myDate = this.Elements.textfield.Value;
DateTime dt = Convert.ToDateTime(myDate);
DateTime dtNew = dt.AddDays(-3);
this.Elements.ChangeDateActive.TypeText(dtNew.ToShortDateString());
That's it thanks

Categories

Resources