Converting string format to datetime in mm/dd/yyyy - c#

I have to convert string in mm/dd/yyyy format to datetime variable but it should remain in mm/dd/yyyy format.
string strDate = DateTime.Now.ToString("MM/dd/yyyy");
Please help.

You are looking for the DateTime.Parse() method (MSDN Article)
So you can do:
var dateTime = DateTime.Parse("01/01/2001");
Which will give you a DateTime typed object.
If you need to specify which date format you want to use, you would use DateTime.ParseExact (MSDN Article)
Which you would use in a situation like this (Where you are using a British style date format):
string[] formats= { "dd/MM/yyyy" }
var dateTime = DateTime.ParseExact("01/01/2001", formats, new CultureInfo("en-US"), DateTimeStyles.None);

You need an uppercase M for the month part.
string strDate = DateTime.Now.ToString("MM/dd/yyyy");
Lowercase m is for outputting (and parsing) a minute (such as h:mm).
e.g. a full date time string might look like this:
string strDate = DateTime.Now.ToString("MM/dd/yyyy h:mm");
Notice the uppercase/lowercase mM difference.
Also if you will always deal with the same datetime format string, you can make it easier by writing them as C# extension methods.
public static class DateTimeMyFormatExtensions
{
public static string ToMyFormatString(this DateTime dt)
{
return dt.ToString("MM/dd/yyyy");
}
}
public static class StringMyDateTimeFormatExtension
{
public static DateTime ParseMyFormatDateTime(this string s)
{
var culture = System.Globalization.CultureInfo.CurrentCulture;
return DateTime.ParseExact(s, "MM/dd/yyyy", culture);
}
}
EXAMPLE: Translating between DateTime/string
DateTime now = DateTime.Now;
string strNow = now.ToMyFormatString();
DateTime nowAgain = strNow.ParseMyFormatDateTime();
Note that there is NO way to store a custom DateTime format information to use as default as in .NET most string formatting depends on the currently set culture, i.e.
System.Globalization.CultureInfo.CurrentCulture.
The only easy way you can do is to roll a custom extension method.
Also, the other easy way would be to use a different "container" or "wrapper" class for your DateTime, i.e. some special class with explicit operator defined that automatically translates to and from DateTime/string. But that is dangerous territory.

Solution
DateTime.Now.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture)

I did like this
var datetoEnter= DateTime.ParseExact(createdDate, "dd/mm/yyyy", CultureInfo.InvariantCulture);

You can change the format too by doing this
string fecha = DateTime.Now.ToString(format:"dd-MM-yyyy");
// this change the "/" for the "-"

The following works for me.
string strToday = DateTime.Today.ToString("MM/dd/yyyy");

Related

Converting a String type to specific DateTime

How do you convert a string such as "2017-12-25T03:31:03.150-08:00" into a DateTime?
DateTime myDate = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff",
System.Globalization.CultureInfo.InvariantCulture);
When you have to follow a predefined pattern while parsing string to DateTime, use DateTime.ParseExact (or DateTime.TryParseExact); in your case:
string source = "2017-12-25T03:31:03.150-08:00";
DateTime result = DateTime.ParseExact(source,
"yyyy-M-d'T'HH:mm:ss.fffzzz",
CultureInfo.InvariantCulture);
I've put M-d (not MM-dd) since the example in the question doesn't provide enough information if month and day must have leading zeroes or not.

DateTime.ParseExact is not doing what i want it to do

When use the .ParseExact() method for the DateTime, i always get the same output as the string i put in. Here is my code:
[Authorize(Roles = "Backoffice, Manager")]
[HttpPost]
public ActionResult FilmShowCreate(FilmShowViewModel newFilmShow)
{
if (ModelState.IsValidField("FilmId") && ModelState.IsValidField("Time"))
{
DateTime unformattedDateTime = newFilmShow.Date.Date + newFilmShow.Time.TimeOfDay;
string dateString = unformattedDateTime.ToString("yyyy-MM-dd HH:mm:ss");
DateTime dbDate = DateTime.ParseExact(dateString, "yyyy-MM-dd HH:mm:ss",
CultureInfo.GetCultureInfo("en-US"), DateTimeStyles.AdjustToUniversal);
FilmShow filmShow = new FilmShow
{
Film = filmRepository.GetFilm(newFilmShow.FilmId),
Cinema = cinemaRepository.GetCinema(newFilmShow.CinemaId),
ThreeDimensional = newFilmShow.ThreeDimensional,
Date = dbDate,
SpecialEvent = newFilmShow.SpecialEvent
};
filmShowsRepository.AddShow(filmShow);
return View("SuccesfullFilmShowCreate");
The string dateString is formatted good, but it is a string and I need to store it in the database as a format DateTime like this "year-month-day hours:minutes:seconds". But for whatever reason the ParseExact doesn't seem to work in my case. The DateTime format i get is "dd-MM-yyyy HH:mm".
It doesn't do what you want because, well, that function isn't supposed to do what you are describing.
ParseExact simply indicates that the input must match the given format in order to be used (and not throw an exception). It is a counterpart to Parse which will accept any valid Date/Time format. It has absolutely no bearing on the future format of any string representation of the DateTime object it creates.
If you want to output it in a given format, pass your format string into ToString before sending that string to the database. Of course, if you are using something like EF, the conversion is done for you and it shouldn't matter.
Example:
string myFormattedDateTime = dbDate.ToString("yyyy-MM-dd HH:mm:ss");
Reading your question more closely, I realize that you seem to think that DateTime has some "stored" format. It does not. DateTime is just a collection of numbers that hold the information required to represent a date and time. The format you are describing only exists in string representations.

Format DateTime object from System time format to required format

My system time is of the format dd-MMM-yy (02-Dec-16). The format I want to convert it to is "yyyy/MM/dd". I've basically been playing around with all the other datetime formats that my system offers and this is the parsing statement I've figured out that works for All of them (except this) -
CultureInfo provider = CultureInfo.InvariantCulture;
string date_format = "yyyy/MM/dd HH:mm:ss tt";
DateTime now_value = DateTime.ParseExact(DateTime.Now.ToString(date_format), date_format, provider);
return now_value.ToString(date_format);
But this doesn't work for the aforementioned dd-MMM-yy format. Can someone please tell me what I am doing wrong here?
(Sidebar -Is there a more efficient way in which I can write this above snippet?)
You don't need to convert DateTime to string and then convert back to DateTime and again back to string, if you have DateTime input just call the ToString with the format as below
string dt =DateTime.Now.ToString("yyyy/MMM/dd", CultureInfo.InvariantCulture);
for your example :
DateTime now_value = DateTime.ParseExact("02-Dec-16", "dd-MMM-yy", System.Globalization.CultureInfo.InvariantCulture);
return now_value.ToString("yyyy/MM/dd");
Try This:
string date_format = "yyyy-MMM-dd";
string date_now = DateTime.Now.ToString(date_format,CultureInfo.CreateSpecificCulture("en-US"));
return date_now;
Even This should also work:
string date_format = "yyyy-MMM-dd";
string date_now = DateTime.Now.ToString(date_format);
return date_now;
I think best way would be to create an extension method for multiple date formats,
var inputDate = "02-Dec-2016";
string[] availaible_input_date_format = { "dd-MMM-yyyy", "dd/MMM/yyyy" }; // add as many formats availible
var date_format = "yyyy/MMM/dd";
DateTime outputDate;
DateTime.TryParseExact(inputDate, availaible_input_date_format, null, DateTimeStyles.None, out outputDate);
Console.WriteLine(outputDate.ToString(date_format));
You can try this:
datetime yourdatetime = new datetime();
string converteddatetime = yourdatetime.toString("yyyy/MM/dd");

C# Datetime format conversion

I have a conversion problem with datetime. I have a date string as MM/dd/yyyy. Now I need to convert it to yyyy-MM-dd.
But I'm facing some error. Please help
public static DateTime ToDBDateTime(string _dateTime)
{
string sysFormat = "MM/dd/yyyy hh:mm:ss tt";
string _convertedDate = string.Empty;
if (_dateTime != null || _dateTime != string.Empty)
{
_convertedDate = DateTime.ParseExact(_dateTime, sysFormat, System.Globalization.CultureInfo.InvariantCulture).ToString(_toDBDateFormat);
//_convertedDate = Convert.ToDateTime(_dateTime).ToString(_toDBDateFormat);
/// Debug.Print(sysFormat);
}
return Convert.ToDateTime(_convertedDate);
}
And I want to know that is there is any way to pass the datetime in various formats and it would return the expected format.
E.g.: if I pass date as dd/MM/yyyy or MM/dd/yyyy, the above function would return the date in format as yyyy-MM-dd.
Please provide some suggestion to solve datetime issues.
I have a date string as MM/dd/yyyy
Right... and yet you're trying to parse it like this:
string sysFormat = "MM/dd/yyyy hh:mm:ss tt";
...
_convertedDate = DateTime.ParseExact(_dateTime, sysFormat,
CultureInfo.InvariantCulture)
You need to give a format string which matches your input - so why are you including a time part? You probably just want:
string sysFormat = "MM/dd/yyyy";
However, that's not the end of the problems. You're then converting that DateTime back into a string like this:
.ToString(_toDBDateFormat)
... and parsing it once more:
return Convert.ToDateTime(_convertedDate);
Why on earth would you want to do that? You should avoid string conversions as far as possible. Aside from anything else, what's to say that _toDBDateFormat (a variable name which raises my suspicions to start with) and Convert.ToDateTime (which always uses the current culture for parsing) are going to be compatible?
You should:
Work out how you want to handle being given an empty string or null, and just return an appropriate DateTime then
Otherwise, just parse using the right format.
This part of your question also concerns me:
E.g.: if I pass date as dd/MM/yyyy or MM/dd/yyyy, the above function would return the date in format as yyyy-MM-dd.
There's no such thing as "the date in format as yyyy-MM-dd". A DateTime is just a date and time value. It has no intrinsic format. You specify how you want to format it when you format it. However, if you're using the value for a database query, you shouldn't be converting it into a string again anyway - you should be using parameterized SQL, and just providing it as a DateTime.
As you have a date in a string with the format "MM/dd/yyyy" and want to convert it to "yyyy-MM-dd" you could do like this:
DateTime dt = DateTime.ParseExact(dateString, "MM/dd/yyyy", CultureInfo.InvariantCulture);
dt.ToString("yyyy-MM-dd");
Use the inbuilt tostring like this:
Convert.ToDateTime(_convertedDate).ToString("MM/dd/yyyy") or whatever format you want.
I tried this and its working fine.
DateTime date1 = new DateTime(2009, 8, 1);
date1.ToString("yyyy-MM-dd hh:mm:ss tt");
You can apply any format in this ToString.
Hope that helps
Milind

Format to be changed in strings

My string contains the value: 08/20/2012-10.32.19
I want the output in string datatype itself as 08/20/2012 10:32:19 [format is MM/dd/yyyy HH:mm:ss].
Please help!!
You may convert the string to DateTime and then use .ToString() with the required format.
DateTime dt = DateTime.ParseExact("08/20/2012-10.32.19", "M/d/yyyy-HH.mm.ss",CultureInfo.InvariantCulture);
string test = dt.ToString("MM/dd/yyyy HH:mm:ss");
Test will have
08/20/2012 10:32:19
EDIT: based on the comment
You may specify multiple date formats and then parse accordingly.
string[] formats = new string[] { "M/d/yyyy-HH.mm.ss", "yyyy-M-d-HH.mm.ss" };
string dtTest1 = DateTime.ParseExact("08/20/2012-10.32.19",
formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None)
.ToString("MM/dd/yyyy HH:mm:ss");
Or in a single line
string dtTest2 = DateTime.ParseExact("08/20/2012-10.32.19",
new string[] { "M/d/yyyy-HH.mm.ss", "yyyy-M-d-HH.mm.ss" },
CultureInfo.InvariantCulture,
DateTimeStyles.None)
.ToString("MM/dd/yyyy HH:mm:ss");
This will satisfy your both case of dates:
08/20/2012-10.32.19
2012-08-20-10.32.19
You may use very simple becouse your string only require fiormating
String a="08/20/2012-10.32.19".Replace('-', ' ').Replace('.', ':');
I hope this work for you
We have various inbuilt format like ToLongDateTime, ToShortdateTime in .Net
string formatDate = txtdte.ToShortDateTime();
This returns string so no need of any other conversion. If you are specific about your format, ToString takes parameters like ToString("dd/mm/yyyy")

Categories