How to convert informal string value to Date time in c# - 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"));

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

Convert date and time into Correct format to compare to current date

I have a date in this format "2017-03-29" and time like "09:30", How do I conver toDatetime.
Following is how I have
string date = "2017-03-29";
string time = "09:30"
I need to convert this to DateTime in c#.
I also need to compare this converted DateTime with current dateTime, I will be using this in comparison in Linq
Use DateTime.ParseExact. Also your problem statement and code shown have nothing to do with Linq. The code below assumes the hours are in 24 hour format, adjust accordingly if that is not the case and provide an am/pm flag.
string date = "2017-03-29";
string time = "09:30";
var dateTime = DateTime.ParseExact(date+time, "yyyy-MM-ddHH:mm", null);
I would say the same as #Sam, but I don't have enough reputation to comment.
string date = "2017-03-29";
string time = "09:30";
string dateTimeString = string.Format("{0} {1}", date, time);
DateTime dateTime = DateTime.ParseExact(dateTimeString, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
Note that the Kind of the resulting DateTime is DateTimeKind.Unspecified. Convert it as necessary.
Using the variables provided:
string dateTime = date + " " + time;
DateTime d = Convert.ToDateTime(dateTime);

Assign value of a string (containing date and time) to two different variable (one for Date and one for Time)

I have a string ("CompletionDate") which contains the value "2/28/2017 5:24:00 PM"
Now I have 2 variables (EDate and ETime). I want to assign the Date to EDate (i.e 2/28/2017) and Time to ETime (i.e. 5:24:00 PM).
How can I split the Date and Time from a single string.
Kindly Help.
My approach right now is like :
string CompletionDate = string.Empty;
string ProjectEDate = string.Empty;
string ProjectETime = string.Empty;
CompletionDate = "2017-03-29 12:58:00";
DateTime dt = DateTime.ParseExact(CompletionDate, "yyyy-MM-dd", CultureInfo.CreateSpecificCulture("en-us"));
DateTime dt1 = DateTime.ParseExact(CompletionDate, "HH:mm:ss", CultureInfo.CreateSpecificCulture("en-us"));
var ProjectEDate = dt.ToString();
var ProjectETime = dt1.ToString();
But its throwing exception that string is not in correct format. Kindly help
#Chris pointed one of your problems, but you have one more. You are passing full date time string and trying to treat it as date or time only, which is not true. Instead I suggest you to parse DateTime object with both date and time, and then take whatever you need from parsed object:
CultureInfo enUS = CultureInfo.CreateSpecificCulture("en-us");
DateTime dt = DateTime.ParseExact(CompletionDate, "yyyy-MM-dd HH:mm:ss", enUS);
var ProjectEDate = dt.Date.ToString();
var ProjectETime = dt.TimeOfDay.ToString();
You need to specify the full format as same as the input string to parse method.
DateTime dt = DateTime.ParseExact(CompletionDate, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.CreateSpecificCulture("en-us"));
To get results you can use below methods available by default in DateTime.
dt.ToShortTimeString()
"12:58 PM"
dt.ToLongTimeString()
"12:58:00 PM"
dt.ToLongDateString()
"Wednesday, March 29, 2017"
dt.ToShortDateString()
"3/29/2017"
Or you can specify the format to ToString method.
dt.ToString("yyyy-MM-dd")
"2017-03-29"
dt.ToString("HH:mm:ss")
"12:58:00"
DateTime.ParseExact(CompletionDate, "yyy-MM-dd", ...
You are missing 4th 'y' in date format string:
"yyyy-MM-dd"
^
here
and:
String was not recognized as a valid DateTime " format dd/MM/yyyy"
Why do you parse into DateTime and then convert to a string using ToString again? CouldnĀ“t you just simply use String.Split when all you want is to split the time from the day and you know the exact format?
var CompletionDate = "2017-03-29 12:58:00";
var tmp = CompletionDate.Split(' ');
var ProjectEDate = tmp[0];
var ProjectETime = tmp[1];

Get yesterday's date from the date entered

I have console application that accepts date as parameter. However, the date is passed as a string in this format:
string dt = DateTime.Now.ToString("yyyyMMdd");
Once the date is entered I need to programmatically get day - 1 from the entered date. Since this is a string, I cannot do any calculation.
For example, user enters:
20141023
I need to subtract a day from the date to get:
20141022
I did a quick fix to solve my immediate need, however, this is not the right way to do it and it has a bug:
int yt = Int32.Parse(dt) - 1;
And then I turn around and convert it yt.ToString()
The above solution will not work if it's the 1st of the month.
Is there a way I can programmatically get yesterday's date in the format (yyyyMMdd) without changing the format and possibly not using the TimeSpan?
Why don't parse the input into a DateTime object? Then you can use the DateTime.AddDays(-1)
For example:
var inputDate = DateTime.ParseExact("20141022", "yyyyMMdd", CultureInfo.InvariantCulture); // change "20141022" into the inputted value
var yesterday = inputDate.AddDays(-1);
var yesterdayString = yesterday.ToString("yyyyMMdd"); // this will be yesterdays date, in the string format
Try this...
DateTime data = DateTime.ParseExact("20141023", "yyyyMMdd", CultureInfo.InvariantCulture);
Console.WriteLine("{0} - {1}", data, data.AddDays(-1).ToString("yyyyMMdd"));
Would this work for you ?
string newDateTimeStr = (DateTime.Today.AddDays(-1)).ToString("yyyyMMdd");
EDIT:
for the date entered by the user:
string txtInputDate = Console.ReadLine();
DateTime dateTime = new DateTime(txtInputDate).ToLocalTime();
string newDateTimeStr = (dateTime.AddDays(-1)).ToString("yyyyMMdd");

Error: No overload for method "ToString" takes 1 arguments

I am trying to format date in a specific order
Time = DateTime.Parse(p.Time.ToString("dd-MM-yyyy HH:mm:ss"))
Data type of Time is DateTime
But i am getting this error:
No overload for method "ToString" takes 1 arguments.
p is the object of the table from which i am getting Time.
List<ProductImageMapWrapper> lstpm = new List<ProductImageMapWrapper>();
lstpm = _db.ProductImageMaps.Where(i => i.ClientId == null && i.BrandId == null).Select(p => new ProductImageMapWrapper
{
Time= // Problem here
}
Now, I tried using it this way
Time = DateTime.Parse(string.Format("{dd-MM-yyyy HH:mm:ss}", p.Time))
but then i got this error:
LINQ to Entities does not recognize the method System.DateTime Parse(System.String) method, and this method cannot be translated into a store expression.
String Time = Convert.ToDateTime(p.Time).ToString("dd-MM-yyyy HH:mm:ss");
It looks to me like the Time property of both types (ProductImageMap and ProductImageMapWrapper) is a DateTime. If that is true, then you should use Time = p.Time
There's a common misconception that a DateTime value somehow has a format. Actually, you apply a given format when you convert the DateTime value into a string. To copy a DateTime value from one place to another, just assign it.
parenthesis are in the wrong place. You cannot parse it as that format. You have to parse P, then format as the string.
DateTime.Parse(System.DateTime.Now).ToString("dd-MM-yyyy HH:mm:ss")
Here is the example how to parse date from string and you can correct this for your structure to work:
string p = "21-11-2013 11:12:13";
DateTime time = DateTime.ParseExact(p, "dd-MM-yyyy HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture);
Considering p.Time as string value in the date format you suggested, I think you want to parse string to DateTime as,
CultureInfo provider = CultureInfo.InvariantCulture;
string format = "dd-MM-yyyy HH:mm:ss"; //This should be format that you get in string
List<ProductImageMapWrapper> lstpm = new List<ProductImageMapWrapper>();
lstpm = _db.ProductImageMaps.Where(i => i.ClientId == null && i.BrandId == null).Select(p => new ProductImageMapWrapper
{
Time = DateTime.ParseExact(p.Time, format, provider)
});
Might Help
var selectQuery=from add in db.address
select add.myDate.toString("{0:dddd, MMMM d, yyyy}");
selectQuery.Distinct();
Normal Convers.
DateTime time = DateTime.Now; // Use current time
string format = "MMM ddd d HH:mm yyyy"; // Use this format
Console.WriteLine(time.ToString(format));
1.MMM display three-letter month
2.ddd display three-letter day of the WEEK
3.d display day of the MONTH
4.HH display two-digit hours on 24-hour scale
5.mm display two-digit minutes
6.yyyy displayfour-digit year
You want to use DateTime.ToString(format) not Nullable.ToString(no
overload):
DateTime? myDate = form.dteStartDate;
string sqlFormattedDate = myDate.Value.ToString("yyyy-MM-dd HH:mm:ss");
Of course this doesn't handle the case that there is no value. Perhaps something like this:
string sqlFormattedDate = myDate.HasValue
? myDate.Value.ToString("yyyy-MM-dd HH:mm:ss")
: "<not available>";

Categories

Resources