DateTime object in a specific format irrespective of the input - c#

I have a ASP.NET MVC app that provides the user to pick a date which is stored into the ViewModel.
This is the code that converts to date object:
viewModel.startDateAndTime = Convert.ToDateTime(buyToday.DealStartDateAndTime);
One of the developers has his system date time set to this format:
24-Feb-2014
On that system he's getting FormatException.
I would like to set the date time to use this format:
mm/dd/yyyy
not matter what the setting is on any system..
Tried using this piece of code which does'nt work:
string startDate = "24-Feb-2014";
DateTime startDateTime = DateTime.ParseExact(startDate, "mmddyyyy", CultureInfo.InvariantCulture);
Any clues are appreciated.
Thanks & Regards.

Your input string does not match parsing pattern.
"24-Feb-2014" is much different then mmddyyyy, isn't it?
You can use DateTime.Parse with CultureInfo.InvariantCulture:
string startDate = "24-Feb-2014";
DateTime startDateTime = DateTime.Parse(startDate, CultureInfo.InvariantCulture);
otherwise, with ParseExact the input has to exactly match pattern, so you should pass 24022014 as input. But, just so you know, mm means minutes. For month, use MM :) So pattern should be ddMMyyyy. Check Custom Date and Time Format Strings page on MSDN.

try this:
string startDate = "24-Feb-2014";
DateTime startDateTime = DateTime.ParseExact(startDate, "dd-MMM-yyyy",System.Globalization.CultureInfo.InvariantCulture);

mm returns The minute, from 00 through 59. So use MM
The month, from 01 through 12.
string startDate = "24-Feb-2014";
DateTime startDateTime = DateTime.ParseExact(startDate, "ddMMyyyy", CultureInfo.InvariantCulture);
Custom Date and Time Format Strings

Related

string to DateTime(date)

I am trying to parse a string i recieved from my webservice into a DateTime so i can look if the date of that datetime is today or not.
I looked a bit and found on msdn and stackoverflow that these possibilities should work, they do not work for me for some reason.
string starttime = obj.TIME; //time i get from webservice = "02/14/2017 00:00:00"
DateTime startTimeCon = DateTime.Parse(starttime);
DateTime startTimeCon2 = Convert.ToDateTime(starttime);
error:
The string is not recognised as a valid DateTime
Any ideas why?
It seems you have different culture in your system.
Use ParseExact() instead of Parse():
DateTime startTimeCon = DateTime.ParseExact(starttime,
"MM/dd/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
HH used for 24 hours, you can use hh for 12 hours
Also, you can set appropriate culture in Parse():
DateTime startTimeCon = DateTime.Parse(starttime, neededCulture);

DateTime string format in c#

I have a project that contain 3 string variables.
DateFormatStr is the format string I need to use to output dates.
DateFormatFrom is the start date a request will apply from
FilloutDateTo is the end date the request will apply to.
The problem is that I don't want to manually specify the dates. As you can see in my example below (a working example), I need to specify the dates, but is there a way to make it that the from date has time 00:00:00 and the end date has time 23:59:59?
string DateFormatStr = "MM/dd/yy hh:mm:ss tt";
string DateFormatFrom = "12/04/14 00:00:00";
string FilloutDateTo = "12/04/14 23:59:59";
So I would like to the system time to recognize the from date and the start date respecting the formatStr variable.
Thanks
If I understand correctly, you can use DateTime.Today property like;
var dt1 = DateTime.Today;
var dt2 = DateTime.Today.AddDays(1).AddSeconds(-1);
and use DateTime.ToString() to format them like;
var DateFormatFrom = dt1.ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
var FilloutDateTo = dt2.ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Results will be;
12/04/2014 00:00:00
12/04/2014 23:59:59
You used hh format specifier but it is for 12-hour clock. Use HH format specifier instead which is for 24-hour clock. And since your result strings doesn't have any AM/PM designator, you don't need to use tt format specifier.
In C# 6.0 you can use string interpolation in order to display formatted dates.
DateTime startOfDay = DateTime.Today;
DateTime endOfDay = DateTime.Today.AddDays(1).AddTicks(-1);
string dateFormatFrom = $"{startOfDay: MM/dd/yy hh:mm:ss tt}";
string filloutDateTo = $"{endOfDay: MM/dd/yy hh:mm:ss tt}";
string idate = "01/11/2019 19:00:00";
DateTime odate = Convert.ToDateTime(idate);
DateTime sdate1 = DateTime.Parse(idate);
string outDate1 = String.Format("{0}/{1}/{2}", sdate1.Day, sdate1.Month,sdate1.Year);
Console.WriteLine(outDate1);

DateTime.ParseExact strings to datetime

I'm about to begin cursing at my computer!
I have one program that output a datetime as a string, but I want to feed it into another as a datetime.
The string I get is on the form:
dd/MM/yy hh:mm:ss
And I would like to find an appropriate way to get a DateTime object back.
I'm thinking something like:
string date = "11/07/14 18:19:20";
string dateformat = "dd/MM/yy hh:mm:ss";
DateTime converted_date = DateTime.ParseExact(date,
dateformat, CultureInfo.InvariantCulture);
But several of the conversion of dates result in an Exception being thrown back with the message "Not valid timedate".
What am I missing?
'hh' for hour is actually 12 hour clock, 01-12. I think you want 'HH' or 'H' for 24-hour clock ('HH' is zero-padded, 'H' is not). Check out: http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx for specific formats.
The hour is not in 12-hour format. For 24-hour format, it's H.
string date = "11/07/14 18:19:20";
string dateformat = "dd/MM/yy H:mm:ss";
DateTime converted_date = DateTime.ParseExact(date,
dateformat, CultureInfo.InvariantCulture);

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

date conversion error

I am developing windows application.
In that i have date in the string format as>> fileDate="15/03/2013"
I want it to be get converted into date format as my database field is datetime.
I used following things for it>>
DateTime dt = DateTime.ParseExact(fileDate, "yyyyy-DD-MM", CultureInfo.InvariantCulture);
DateTime dt = DateTime.Parse(fileDate);
Both of these methods proved failure giving me error>>
String was not recognized as a valid DateTime.
What can be mistake?
Is there another technique to do that?
string fileDate = "15/03/2013";
DateTime dt = DateTime.ParseExact(fileDate, "dd/mm/yyyy", CultureInfo.InvariantCulture);
You have to give the date format according to the date string you have to ParseExact. You can see more on Custom DateTime format - MSDN
Change
"yyyy-MM-dd HH:ss"
To
"dd/MM/yyyy"
Your code would be
DateTime dt = DateTime.ParseExact(fileDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
You should do this:
DateTime dt = DateTime.ParseExact(fileDate, "dd/MM/yyyy",CultureInfo.InvariantCulture);
You must pass in the string for the format ("dd/MM/yyyy") in the same style that you pass in the string fileDate.
u may try with this
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate = dateFormat.parse("ur_dateString")
In your current code you are using format "yyyyy-DD-MM" which is wrong since date part require lower case d not upper case D. , Also for year part you are specifying 5 ys, it should be 4, like yyyy, the order according to your date string should be: "dd/MM/yyyy". To be on the safe side you can even use "d/M/yyyy", which would work for single digit or double digit day/month.
So your code should be:
string fileDate="15/03/2013";
DateTime dt = DateTime.ParseExact(fileDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
You can see more on Custom DateTime format - MSDN
It's because string "15/03/2013" cannot really be parsed as DateTime with format string "yyyy-MM-dd HH:ss".

Categories