Retaining MM/DD/YYYY format in String - c#

I need to write date in MM/DD/YYYY format. From a Date Picker Control. I try to assign it to a DateTime variable. Before Writing it to a file I assign it to a string. I see the value stored in String variable is in DD/MM/YYYY format.
Below is assignment statement
DateTime startTime, endTime;
string startTimeDate = "";
startTime = Convert.ToDateTime(dpStartTime.Value.ToString("MM/dd/yyyy HH:mm"));
endTime = Convert.ToDateTime(dpEndTime.Value.ToString("MM/dd/yyyy HH:mm"));
startTimeDate = startTime.ToString("MM/dd/yyyy HH:mm");
startTimeDate = startTimeDate.Replace('-', '/');
I observe startTimeDate is stored as DD/MM/YYYY only. startTime is storing as MM/DD/YYYY format only. Please let me know if there is any other approach to correctly assign / convert the date values.
Thanks in Advance

Edit:
You are losing the original date in your Convert.DateTime() conversion, you have to apply the format string here as well e.g. using DateTime.ParseExact :
startTime = DateTime.ParseExact(dpStartTime.Value.ToString("MM/dd/yyyy HH:mm"),
"MM/dd/yyyy HH:mm",
CultureInfo.InvariantCulture);

Instead of using Convert.ToDateTime(), try to use DateTime.ParseExact(string s, string format, IFormatProvider provider) when you can ensure the datetime format and want to ignore the system settings. MSDN Reference for the DateTime.ParseExact() method can be found here

You're converting DateTime to string, then you're converting it again to DateTime using Convert class. You're not preserving the format here cause DateTime is format agnostic. And default ToString conversion (used by debugger) is in your cause MM/DD/YYYY.

I usually use String.Format, ex
String.Format("{0:d/M/yyyy HH:mm:ss}", dpStartTime.Value);
To format dates as strings.

Related

String Date To convert DateTime using ParseExact

I have a string and it comes as a DD/MM/YYYY style.(eg : 11/07/2018)
I need to convert this To DateTime format and YYYY-MM-DD style.
I tried it using DateTime.Parse but can't
if (!String.IsNullOrEmpty(fromDate))
{
frm = DateTime.ParseExact(fromDate, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None);
}
else if(!String.IsNullOrEmpty(toDate))
{
todt = DateTime.ParseExact(toDate, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None);
}
You can do this in one line of code.
var newDateString = DateTime.ParseExact(myDateString, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("yyyy-MM-dd");
Keep in mind that a DateTime instance is a data structure that does not have a format. When dealing with dates and times it is best to only revert to a human readable string when you need to present/output the value for a human to read. For anything else including persistence to a storage system that supports types (like a relational database) leave the value as a DateTime type.
Example: If you wanted yyyy-MM-dd because you wanted to persist this to Sql Server then you should stop after the parsing (and not call ToString). You can then assign the DateTime instance to a command parameter's Value property directly.
Convert using ParseExact and then use ToString to the target format:
string dateS = "30/04/2018";
DateTime dateD = DateTime.ParseExact(dateS, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
string dateS2 = dateD.ToString("yyyy-MM-dd");
Here is a working example in fiddle: https://dotnetfiddle.net/e0yuZ6

How to convert string to given date format

The below code is in MM/DD/YYYY format
string dateStr="9/7/1986";
But i want to change it like below format
dateStr="09/07/1986";
again same in MM/DD/YYYY format
This code should work for you.
string dateStr = "9/7/1986";
string newDateStr= DateTime.Parse(dateStr).ToString("MM/dd/yyyy");
newDateStr will hold the value you need.
The best thing to do would be to use that format when you first convert the DateTime value to a string. Although, this would only work if you had it as a DateTime variable first.
You could parse it to a DateTime then format it back to a string.
dateStr = DateTime.ParseExact(dateStr, "M/d/yyyy", CultureInfo.InvariantCulture)
.ToString("MM/dd/yyyy");
Note that you'll get exceptions if the string doesn't match the M/d/yyyy format.

Converting this string format to a valid DateTime?

The string in question: "2003:12:14 12:01:44" (yyyy:MM:dd hh:mm:ss)
How would I be able to convert this to a valid datetime in C#? I tried Convert.ToDateTime(str), but to no avail.
Use the right DateTime format and supply DateTime.ParseExact with that format. Note that since your time doesn't show AM or PM, it may be safer to assume that it uses 24-Hr format (use capital HH) than 12-Hr AM PM (not hh) format. The following code should work:
string format = "yyyy:MM:dd HH:mm:ss"; //note: use HH not hh
var result = DateTime.ParseExact("2003:12:14 12:01:44", format, CultureInfo.InvariantCulture);
Check more on the available DateTime formats here (standard) and here (custom).
Convert.ToDateTime try to parse your string as a standard date and time format of your CurrentCulture settings. Looks like this string is not a standard format.
You can use DateTime.ParseExact for specify custom format.
var dt = DateTime.ParseExact("2003:12:14 12:01:44",
"yyyy:MM:dd hh:mm:ss",
CultureInfo.InvariantCulture);

DateTime Conversion and Parsing DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff")

I store some DateTime in a CSV log with:
DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff")
When I try to read it I found something like:
"05/15/2012 10:09:28.650"
The problem is when I try to cast it as a DateTime again...
DateTime.Parse("05/15/2012 10:09:28.650");
Throws an Exception "Invalid DateTime" or something like that...
How can I properly re-read the DateTime?
You can use DateTime.ParseExact:
string format = "MM/dd/yyyy hh:mm:ss.fff";
DateTime d = DateTime.ParseExact("05/15/2012 10:09:28.650",
format,
System.Globalization.CultureInfo.InvariantCulture);
Standard Date and Time Format Strings
use DateTime.ParseExact with specifying the format
String dateStr=DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff");
DateTime date = DateTime.ParseExact(dateStr,"MM/dd/yyyy hh:mm:ss.fff",System.Globalization.CultureInfo.InvariantCulture);
You should use this method to parse your string. You would have to make a class, imlementing IFormatProvider, but if you want to use a custom DateTime format, it's the best method I can think of.

How to Convert Date Object with Format "MM/dd/yy hh:mm:ss tt" to DateObject with Format "dd/MM/yy

I have googled alot and tried lot of solutions but nothing is working for me.For Ex i Have tried below :
public static DateTime ParseDateToSystemFormat(DateTime date)
{
IFormatProvider culture = new CultureInfo("en-GB", true);
DateTime dt = DateTime.ParseExact(date.ToString("dd/MM/yyyy"),
"dd/MM/yyyy",
culture,DateTimeStyles.NoCurrentDateDefault);
return Convert.ToDateTime(dt,culture);
}
If anyone have solved this please let me know.
Date objects do not have formatting associated to them - you only use formatting for display.
When it is time to display the DateTime object, use either custom or standard format strings to format the display to your liking.
What you are doing here:
DateTime dt = DateTime.ParseExact(date.ToString("dd/MM/yyyy"),
"dd/MM/yyyy",
culture,DateTimeStyles.NoCurrentDateDefault);
Is rather strange - you are getting a specific string representation of your DateTime - date.ToString("dd/MM/yyyy"), then parsing that string back to a DateTime object. A bit of a long way to say DateTime dt = date;, with clearing out the hours/minutes/seconds data.
If you simply want the date portion of a DateTime, use the Date property. It produces:
A new object with the same date as this instance, and the time value set to 12:00:00 midnight (00:00:00).
The internal representation of a DateTime is always the same. There is no formatting attached to a DateTime object.
If it is only a display problem, then convert the DateTime to a string and display that string. You already know how to do it: Using ToString and specifying the format you want to have.

Categories

Resources