Best way to bind DateTime to seperate date and time fields? - c#

I use a model class with a DateTime value. I would like to display this property as two boxes, one for the date and the other one for the time.
What is the best way to do this? Any suggestions?
Thanks in advance!

Check this Splitting DateTime Blog post by Hanselman.

Format your datetime in 2 diffent properties.
first to retrieve datetime format as "yyyy/MM/dd"
second format as "HH:mm:ss"

All you need to do is use two format expressions, one to extract the time and the other to extract the date.
Bind this to the date box:
txtDateBox.Text = date.ToString("dd MMM yyyy");
Bind this to the time box:
txtTimeBox.Text = date..ToString("HH:mm:ss");
(Presumign your variable is called date).

You could do something like this (I didn't run the code, it's only an idea):
private DateTime MyModelDateTime;
public string date
{
get
{
return MyModelDateTime.ToString("MM/dd/yyyy");
}
set
{
string pattern = "MM/dd/yyyy HH:mm:ss";
string timeValue = MyModelDateTime.ToString("HH:mm:ss");
string dateTimeValue = value + " " +timeValue;
MyModelDateTime = DateTime.ParseExact(dateTimeValue, pattern, null, DateTimeStyles.None)
}
}
public string time
{
get
{
return MyModelDateTime.ToString("HH:mm:ss");
}
set
{
string pattern = "MM/dd/yyyy HH:mm:ss";
string dateValue = MyModelDateTime.ToString("MM/dd/yyyy");
string dataTimeValue = dateValue + " " + value;
MyModelDateTime = DateTime.ParseExact(dateTimeValue, pattern, null, DateTimeStyles.None)
}
}

Related

How to show date in diffrent way in GridView?

I'd like to change DisplayFormat in my grid from
"MM/dd/yyyy"
to
"yyyy/MM/dd hh:mm:ss"
but nothing happens.
You should use this (example):
static void Main()
{
DateTime time = DateTime.Now; // Use current time.
string format = "yyyy/MM/dd hh:mm:ss"; // Use this format.
Console.WriteLine(time.ToString(format)); // Write to console.
}
So when inserting your data in the GridView, you convert it to a string with the selected format.
Here's the link for multiple date format and how to use them: https://www.dotnetperls.com/datetime-format
It is easier for me to answer my question than isolated working code in my complex program. So this is my hack that works inside my program:
private void GridView_CustomDrawEvent(object sender, RowCellCustomDrawEventArgs e)
{
if(e.Column.FieldName == "CreationDate")
{
string date = ((DateTime) view.GetRowCellValue(e.RowHandle, "CreationDate"));
string displayDate = date.ToShortDateString() + " " time.ToLongTimeString();
e.DisplayText = displayDate;
}
}
I catch my DateTime object in CustomDrawCell event and I am translating it to string using two standard methods DateTime.ToShortDateString() and DateTime.ToLongTimeString(). Thanks very much for your time.
Settings
Set Display format
dd-MMM-yyyy hh:mm:ss tt
Result

C#: Is this possible to convert 24hrs format string Datetime to 12hrs AM/PM dateformat (again in string only)

I have a date/time return from a C# method is in string,
string dateTime = "2018-6-18 20:50:35"
Now I would like to convert this into another string representation like,
string convertDT = "2018-6-18 08:50:35 PM"
Is this possible?
Seems like I can do something like,
var formattedTime = dateTime.ToString("h:mm tt", CultureInfo.InvariantCulture);
but not working. Suggestion please!
Just parse the string into a new DateTime object and then call ToString() with the right formats:
string dateTime = "2018-6-18 20:50:35";
DateTime parsedDateTime;
if(DateTime.TryParse(dateTime, out parsedDateTime))
{
return parsedDateTime.ToString("yyyy-M-d hh:mm tt");
}
The benefit of my answer is that it contains validation (DateTime.TryParse()), it results in a couple extra lines of code but you can now accept all input and not worry about an exception being thrown.
Even better would be to refactor this logic into its own method that you can re-use:
public static bool TryChangeDateTimeFormat(string inputDateString, string outputFormat, out string outputDateString)
{
DateTime parsedDateTime;
if(DateTime.TryParse(inputDateString, out parsedDateTime))
{
outputDateString = parsedDateTime.ToString(outputFormat);
return true;
}
outputDateString = string.Empty;
return false;
}
This returns a bool of whether or not the conversion was successful and the out variable will be modified depending on the result.
Fiddle here
Without adding any validation,
var string24h = "2018-6-18 20:50:35";
var dateTime = DateTime.Parse(string24h);
var formattedTime = dateTime.ToString("h:mm tt", CultureInfo.InvariantCulture);
Use DateTime.ParseExact and then ToString
Sure, you can use the DateTime class to parse the original string and then output a differently formatted string for the same date:
string result = DateTime.Parse(dateTime).ToString("h:mm tt", CultureInfo.InvariantCulture);
var dateTime = "2018-6-18 20:50:35";
var dt = Convert.ToDateTime(dateTime);
var amPmDateTime = dt.ToString(#"yyyy-MM-dd hh:mm:ss tt", CultureInfo.InvariantCulture);
To give you exactly your format you would use
string convertDT = DateTime.Parse(dateTime).ToString("yyyy-MM-dd hh:mm:ss tt");
You can change the format between the quotes however you would like. For example yyyy/MM/dd or something. Just remember MM is 2 spots for months and mm is 2 spots for minutes.
So if you put
string convertDT = DateTime.Parse(dateTime).ToString("yyyy-mm-dd hh:mm:ss tt");
You are going to get year - minutes - days.

Convert string of date format to string of another date format

I want to convert a string of date format to a string with another format.
The string DateOfBirth could be in different formats such as:
01/15/2017
01-15-2017
1.15.2017
1.5.2017
I want to convert it to another pattern that I get it as parameter.
public string ConvertStringDateFormat(string date, string convertToDateFormat)
{
}
Let's assume that date = "01/15/2017" and convertToDateFormat = "YYYY/MM/DD". How could I change it to the new format?
The problem for me was to do it generic so that it will accept any parametrs.
I thought that I can convert date to DateTime and then to use ToString with the format but can you offer any better idea?
Parse to DateTime and then back to String:
public string ConvertStringDateFormat(string date, string convertToDateFormat) {
return DateTime
.ParseExact(date,
new string[] { "M/d/yyyy", "M-d-yyyy", "M.d.yyyy" },
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal)
.ToString(convertToDateFormat); // convertToDateFormat = #"yyyy\/MM\/dd" for YYYY/MM/DD
}
i think this will work :
(Convert.ToDateTime(date)).ToString(convertToDateFormat)
try this
public string ConvertStringDateFormat(string date, string convertToDateFormat)
{
return Convert.ToString(Convert.ToDateTime(date),convertToDateFormat);
}

Failing when casting to DateTime object

I have this CSV
"06/04/2016 17:24:14,1443.92,0.31"
Which I try to convert into the following object
public class FooModel
{
public DateTime Date { get; set; }
public DateTime Time { get; set; }
public string Index { get; set; }
public string Change { get; set; }
}
with the following code
string[] values = line.Split(',');
FooModel m = new FooModel
{
Date = DateTime.ParseExact(values[0], "dd/MM/yyyy", CultureInfo.InvariantCulture),
Time = DateTime.ParseExact(values[0], "H:mm:ss", CultureInfo.InvariantCulture),
CultureInfo.InvariantCulture),
Index = values[1],
Change = values[2],
};
and failing on the exception
"String was not recognized as a valid DateTime."
How can I cast to DateTime Object
EDIT
I saw couple of answers that almost worked however it was my bad to mention that the date is formatted as Day-Month-Year. this means that it is failing when the csv is set to "22/12/2014 16:24:04,1476.83,-0.74"
I would guess the issue you're having is with the ParseExact part of this.
Why are you converting both the date and the time separately? It seems easier to do this:
DateTime Date = DateTime.Parse(values[0]);
string time = Date.ToLongTimeString();
string date = Date.ToLongDateString();
This way it's saved in the same variable and you can use the pieces as you need.
From the documentation:
The format of the string representation must match the specified format exactly.
The input string is:
"06/04/2016 17:24:14,1443.92,0.31"
The format string is:
"dd/MM/yyyy"
Those aren't really exact. Just use Parse instead:
Date = DateTime.Parse(values[0]);
This gives you the complete DateTime value, so you don't even need the Time property on the model. No need to store the same information twice, after all.
Additionally, you might use TryParse to be a little safer with the input:
DateTime temp;
if (!DateTime.TryParse(values[0], out temp))
{
// parsing error. notify the user?
}
Date = temp;
string[] s = "06/04/2016 17:24:14,1443.92,0.31".Split(',');
DateTime date = DateTime.Parse(s[0]);
This worked for me.
When you split the string values[0] = 06/04/2016 17:24:14 and you are parsing the Date and the Time component separately. Instead you need to parse them together with
DateTime date = DateTime.ParseExact(values[0], "dd/MM/yyyy H:mm:ss",
CultureInfo.InvariantCulture);
and access the date by
date.Date
and access the time by
date.Time

SQL formatted date time not returning time

I'm using the following to get the time/date of now to be in a nice format for sql insert. The dates working fine but the times always returning 0:0:0.
public static String getDateString()
{
DateTime time = DateTime.Now;
String sqlFormattedDate = time.Date.ToString("yyyy-MM-dd HH:mm:ss");
return sqlFormattedDate;
}
That happens, because you're using the Date, and not the DateTime:
Just leave the Date-Part and it will be working as expected.
public static String getDateString()
{
DateTime time = DateTime.Now;
String sqlFormattedDate = time.ToString("yyyy-MM-dd HH:mm:ss");
return sqlFormattedDate;
}
Problem : You are trying to get the Date and Time from the Date value.
time.Date contains only Date not Time that is why you are always getting 0:0:0 as a time.
Solution: You need to call ToString("yyyy-MM-dd HH:mm:ss") function on DateTime variable time directly.
Try This:
public static String getDateString()
{
DateTime time = DateTime.Now;
String sqlFormattedDate = time.ToString("yyyy-MM-dd HH:mm:ss");
return sqlFormattedDate;
}
That is caused by your instruction.
String sqlFormattedDate = time.Date.ToString("yyyy-MM-dd HH:mm:ss");
As you can see here on the official Microsoft documentation, by using the property "Date" of the time object you are using only the date part of actual date-time value. Basically .Date is returning a "new instance" where the time part has been set to the default 00:00:00.
Just remove the ".Date" part so that the instruction looks like below and it should work:
String sqlFormattedDate = time.ToString("yyyy-MM-dd HH:mm:ss");
USe
String sqlFormattedDate = time.ToString("yyyy-MM-dd HH:mm:ss");

Categories

Resources