Format to be changed in strings - c#

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

Related

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

Parse String date to specific format

This is a String date:
dob = reader.GetValue(7).ToString();` return like "12/2/2012"
But I want to convert (before passing it) to this format "2012212", I have tried
string newDate = dob.ToString("yyyMMdd")
But I got the following error:
The best overloaded method match for
'string.ToString(System.IFormatProvider)has some invalid arguments
any idea ?
Not Exact way of getting output but it will work.
string dob = "12/2/2012";
string[] d1 = dob.Split('/');
string s = d1[2] + d1[1] + d1[0];
You could use SqlDataReader.GetDateTime if underlying return type is DateTime
Then you just need..
reader.GetDateTime(7).ToString("yyyyMdd");
In case, if it is stored and received as a string then I would suggest converting to DateTime first and then look for specific format.
var date = DateTime.ParseExact(dob, "dd/M/yyyy",CultureInfo.InvariantCulture);
var formattedDate = date.ToString("yyyyMdd");
DateTime.ParseExact(reader.GetValue(7), "dd/M/dd", System.Globalization.CultureInfo.InvariantCulture).ToString("yyyyMMdd");
If you have a date in a String with the format "ddMMyyyy" and want to convert it to "yyyyMMdd" you could do like this:
DateTime dt = DateTime.ParseExact(dob, "ddMMyyyy",
CultureInfo.InvariantCulture);
dt.ToString("yyyyMMdd");
You can try below method to convert string to date.
IFormatProvider culture = new CultureInfo("en-US", true);
dob = DateTime.ParseExact(reader.GetValue(7).ToString(), "dd/MM/yyyy", culture).ToString("yyyyMMdd");
Thank you.

Convert YYYYMMDD string to MM/DD/YYYY string

I have a date that is stored as a string in the format YYYYDDMM. I would like to display that value in a 'MM/DD/YYYY' format. I am programming in c#. The current code that I am using is as follows:
txtOC31.Text = dr["OC31"].ToString().Trim();
strOC31date = dr["OC31DATE"].ToString().Trim();
DateTime date31 = DateTime.Parse(strOC31date);
strOC31date = String.Format("{0:MM/dd/yyyy}", date31);
However, I am getting an error because the YYYYMMDD string (strOC31date) is not being recognized as a valid datetime.
DateTime.ParseExact with an example
string res = "20120708";
DateTime d = DateTime.ParseExact(res, "yyyyddMM", CultureInfo.InvariantCulture);
Console.WriteLine(d.ToString("MM/dd/yyyy"));
Use ParseExact() (MSDN) when the string you are trying to parse is not in one of the standard formats. This will allow you to parse a custom format and will be slightly more efficient (I compare them in a blog post here).
DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyMMdd", null);
Passing null for the format provider will default to DateTimeFormatInfo.CurrentInfo and is safe, but you probably want the invariant culture instead:
DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
Then your code will work.
Instead of DateTime.Parse(strOC31date); use DateTime.ParseExact() method, which takes format as one of the parameters.
You want the method DateTime.ParseExact.
DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyddMM", CultureInfo.InvariantCulture);

Converting string format to datetime in mm/dd/yyyy

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

Categories