Invert position of time and date [duplicate] - c#

This question already has answers here:
Convert System DateTime to specific format. eg:(yyyyMMdd hh:MM:ss)
(5 answers)
Closed 2 years ago.
If I have a datetime standard (dd/MM/yyyy hh:mm:ss) is there a possible to invert position of time and date and get hh:mm:ss dd/MM/yyyy ?
I tried
var tempDate = date.ToString("hh:mm:ss dd/MM/yyyy");
date = Convert.ToDateTime(tempDate);
But I keep get the date in first format (dd/MM/yyyy hh:mm:ss).
New Info
As per conversation with the OP, the motivation here is that the date needs to be displayed in the grid in the specific format. The model that contains DateTime Property is part of the list. Question is, "How to make date appear in the specific format in the grid?"

Lets walk this one. Here you have a date you presenting as a string in a specific format
var tempDate = date.ToString("hh:mm:ss dd/MM/yyyy");
This, I am not sure why it is working for you at all without supplying Format Provider
date = Convert.ToDateTime(tempDate);
This program did not work for me (as expected!) because the culture of my thread (format provider) does not have parsing mechanism to such string as I receive from the line 1
var tempDate = DateTime.Now.ToString("hh:mm:ss dd/MM/yyyy");
Console.WriteLine(tempDate); // Prints the date
var date = Convert.ToDateTime(tempDate); //ERROR !!!
Console.WriteLine(date);
DateTime is not stored in any specific format. It is a special data type. What you see on the screen is a string representation of this type. Here Console.WriteLine(date);, as example, date being converted to a string using its internal logic in default ToString() implementation, using current thread's culture. Or you can use ToString(...) parameterized overloads to get out a specific format, e.g. "hh:mm:ss dd/MM/yyyy". But storing this format in DateTime is not possible. Format comes from the culture, which your thread currently is set with, unless you specify it. You can try to change culture on the thread and you will see different results from ToString() for each culture.
To Answer the question as it came up from conversation with OP, you can do the following
// imagine this is as original model
public class DataModel
{
// Other propertues here
public DateTime DateProperty { get; set; }
}
// create display model
public class DisplayModel
{
privvate const string _format = "hh:mm:ss dd/MM/yyyy";
private DataModel _dataModel;
public DisplayModel(DataModel dataModel)
{
_dataModel = dataModel;
}
// Wraps date time and
public string DateProperty { get { return _dataModel.ToString(_format); } }
// other properties here
}
This is possible general approach for whatever UI needs. However, if the grid you've mentioned is DataGridView, even simpler approach would be is to set a property on the grid
dataGrid.Columns[0].DefaultCellStyle.Format = "hh:mm:ss dd/MM/yyyy";

Related

Use correctly String.Format - C#

I have two objects of type string, where I retrieve a date in dd/MM/yyyy format, I need to format this date I'm getting to show only month and year, in order to use this object in a groupby to group records by month. I'm doing it as follows, retrieving the date in another object to apply the formatting:
//Object where I retrieve the date with dd/MM/yyyy normally
public string DataCupom { get; set; }
//Object where I retrieve the value of DataCupom and I'm trying to apply the formatting
public string DataCupomAgrupadoMes { get { return String.Format("{MM:yyyy}", DataCupom); }
How can I apply String.Format correctly to retrieve only month and year?
A string is just a sequence of characters. It has no "date" or "time" semantics. Thus, attempting to format a sequence of characters (sucha as the DataCupom string) like it being some data type representing dates or time is not going to work.
In your case, one of the simplest approaches would probably be splitting the DataCupom string using '/' as separator, and then assemble the new required string from those parts of the split which represent month and year.
var parts = DataCupom.Split('/');
return $"{parts[1]}:{parts[2]}";
You can try parsing dateString to DateTime and then format.
DateTime dateTime = DateTime.Parse(dateString);
dateTime.ToString("MM/yyyy");
String.Format() uses numeric placeholders:
return String.Format("{0:MMyyyy}", DataCupom);
Where the 0 in the format string means to look at the first additional argument position for the value.
You can also use interpolation:
return $"{DataCupom:MMyyyy}";
or a simple ToString() call:
return DataCupom.ToString("MM:yyyy");

How to get DateTime Format String of actual date-time?

I'd like to take a datetime string, and get the string version of its format:
e.g. 2017-01-02 would yield YYYY-MM-dd for logging purposes if a datetime is parsed incorrectly due to a parsing exception.
Is this possible with System.DateTime or any other built-in?
"2017-01-02" would yield "YYYY-MM-dd"
It's not possible. You are asking for magic, making something out of nothing.
There is no way without meta information for a computer (or a human) to decide if that is the 2nd January or the 1st February. Both is possible.
There is no reliable way of getting that format string based on a string that might look like a date.
The closest hack that I can come up with is iterating over all cultures and then trying to ParseExact the predefined DateTime patterns that are found in each culturinfo's DateTimeFormat property.
The hack would look like this:
var date = "2017-01-02";
var formats = new Dictionary<string,int>();
// go over all cultures
foreach(var ci in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
{
// each culture has a DateTimeFormatInfo that holds date and time patterns
foreach(var p in typeof(DateTimeFormatInfo)
.GetProperties()
.Where(prop => prop.Name.EndsWith("Pattern")))
{
// get a pattern property from the cultureinfo DateTimeFormat
var fmt = (string) p.GetValue(ci.DateTimeFormat, null);
try
{
// try to parse the date
DateTime.ParseExact(date,fmt , ci);
// add the format
if (formats.Keys.Contains(fmt))
{
formats[fmt]++; // how often this was a valid date
}
else
{
formats.Add(fmt, 1); // first time we found it
}
}
catch
{
// no date in this culture for this format, ignore
}
}
}
// output the formats that were parsed as a date
foreach(var kv in formats)
{
// Dump is a linqPad extension, use Console.WriteLine if that bothers you
kv.Value.Dump(kv.Key);
}
and on my box this returns
yyyy-MM-dd
40
yyyy-M-d
1
Now for 01/02/2017 it would return:
dd/MM/yyyy
255
d/M/yyyy
93
M/d/yyyy
20
d/MM/yyyy
11
MM/dd/yyyy
2
which shows a bit of the concerns raised in the comments. Without knowing the culture a date string was generated it is a guess what the date format was. Worst case it was a string with numbers and dashes between them.

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.

Converting DateTime [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to convert DateTime object to dd/mm/yyyy in C#?
I'm new to c# and was hoping someone could help me clean up some code.
I have the following method which converts a DateTime to a custom Event string e.g. 30th of Jan 2012 is converted to 201201 (ignores the day)
public ConvertToEventDate(DateTime date)
{
var year = date.Year.ToString();
var month = date.Month.ToString();
month = month.Length == 2 ? month : "0" + month;
return year + month;
}
I was wondering if there is a better way of doing this conversion.
I'd do this;
public string ConvertToEventDate(DateTime date)
{
return date.ToString("yyyyMM");
}
you can also put this into an Extension method like this;
public static class ExtenstionMethods
{
public static string ToEventDate(this DateTime date)
{
return date.ToString("yyyyMM");
}
}
and then call it ike this;
DateTime date = new DateTime(2012, 30, 1);
date.ToEventDate();
as opposed to this;
ConvertToEventDate(date);
public string ConvertToEventDate(DateTime date)
{
return date.ToString("yyyyMM", CultureInfo.InvariantCulture);
}
Have a look at the custom formatting strings docs
Others have suggested ToString("yyyyMM") which is basically there - but I would suggest you probably want to specify the invariant culture. Otherwise if the thread's current culture uses a non-Gregorian calendar, you could end up with a month/year you're not expecting. So I'd use:
string text = date.ToString("yyyyMM", CultureInfo.InvariantCulture);
See the documentation for custom date and time format strings for more information if you want to change the exact format later.
Try
return date.ToString("yyyyMM");

convert string to date without time

This line
System.DateTime.Parse("09/12/2009");
convert date (string) to 9/12/2009 12:00:00 AM. How can I get a date in the form 9/12/2009.
after explanations I do:
DateTime dt = System.DateTime.Parse(Request.Form["datepicker"]);
dt.ToString("dd/mm/yyyy");
/* and this code have time, why???*/
Your problem is not with the parsing but with the output. Look at how ToString works for DateTime, or use this example:
using System;
class Program
{
static void Main(string[] args)
{
DateTime dt = DateTime.Parse("09/12/2009");
Console.WriteLine(dt.ToString("dd/MM/yyyy"));
}
}
Or to get something in your locale:
Console.WriteLine(dt.ToShortDateString());
Update: Your update to the question implies that you do not understand fully my answer yet, so I'll add a little more explanation. There is no Date in .NET - there is only DateTime. If you want to represent a date in .NET, you do so by storing the time midnight at the start of that day. The time must always be stored, even if you don't need it. You cannot remove it. The important point is that when you display this DateTime to a user, you only show them the Date part.
Anything parsed to a DateTime object will contain date+time. If no time is sepcified, the assumed value will be 0000hr.
To get the date-only representation, it's up to how you format it to string.
E.g. theDate.ToString("dd/MM/yyyy")
Refer to the MSDN Date and Time Format Strings.
if you want to convert gridview datetime column to date only column use this code :
raddgvDaybook.Rows.ToList().ForEach(x =>
{
DateTime dt = DateTime.Parse(x.Cells["Vocdate"].Value.ToString());
string str = string.Format("{0:MM/dd/yyyy}", dt);
x.Cells["Vocdate"].Value = str;
});
I tested the code it will work if you bind the datetime as string in dgv.

Categories