How to convert string to given date format - c#

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.

Related

how to convert dash or any date format into slash datetime

string strDate = 16-08-1979 i.e dd-MM-yyyy
Datetime Dob=DateTime.Parse(strDate.ToString() , new CultureInfo("en-US", false));
I want every format convert into "MM/dd/yyyy"
Given the example you provided, there's a few steps you'd need to take first.
Your strDate value isn't a data type, so make it a string.
string strDate = "16-8-1979";
This is already a string that's in a bad format, but we can parse it to a DateTime value to work with.
DateTime.TryParse(strDate, out DateTime myDate);
Now we've got a DateTime to work with, we can output a properly formatted string with the value.
string output = myDate.ToString("MM/dd/yyyy"); // output should be 08/16/1979

ParseExact Not working

I am trying to convert my string to datetime using ParseExact method but it is not working as expected, Date format in the string is "dd/MM/yyyy" but when i use parseExact method, it changes the format to "MM/dd/yyyy". i want to keep my date format as it is in the string and just want to change string to DateTime. here is my code given below.
string FormattedDate = "18/03/2017";
var parsed = DateTime.ParseExact(FormattedDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
It returns "03/18/2017", how i can keep it same.
please help.
Thanks
It is working, since the input string is parsed as DateTime object. You can't change the format of the DateTime object but you can get the value into any format by using format strings.
string oldFormat = parsed.ToString("dd/MM/yyyy");
string anotherFormat = parsed.ToString("yyyy-MMMM-dd");

Parse string value to datetime value

I need to parse string value to date time value, I have date in this format:
DD.MM.YYYY
I want to parse value in this format:
YYYY-MM-DD
I tried to do it like this:
DateTime.ParseExact(date_req, "yyyy-MM-dd", CultureInfo.InvariantCulture);
But i have an error: String was not recognized as a valid DateTime.
Is there a way to do this?
If you have a string in the format DD.MM.YYYY why are you passing YYYY-MM-DD to your ParseExact function?
Try like this:
string dateStr = "12.06.2012";
DateTime date = DateTime.ParseExact(dateStr, "dd.MM.yyyy", CultureInfo.InvariantCulture);
Then when you want to output this DateTime instance somewhere you could use the YYYY-MM-DD format, like this:
string result = date.ToString("yyyy-MM-dd");
I think what you want to do is parse your dd.MM.yyyy and then display it as yyyy-MM-dd.
You first have to parse the string into a DateTime:
DateTime date = DateTime.ParseExact(date_req, "yyyy-MM-dd", CultureInfo.InvariantCulture);
Now date is a representation of the date that the computer actually understands (before it was just a string). You can now display this object anyway you want:
string yyyyMMdd = date.ToString("yyyy-MM-dd");
string arabic = date.ToString("yyyy-MM-dd", new CultureInfo("ar"));
// and so on
Don't forget that when converting dates from strings to DateTime and back, culture and time zones are worth keeping in mind.
When parsing a date you need to specify the format you want to read, not the format you want as output later.
So use dd.MM.yyyy as argument to ParseExact.
Check DateTime.ParseExact Method (String, String,
IFormatProvider) Converts the specified string representation
of a date and time to its DateTime equivalent. The format of the
string representation must match a specified format exactly or an
exception is thrown.
you have to specify format string as DD.MM.YYYY rather than "yyyy-MM-dd".
try this:
DateTime dateValue = DateTime.ParseExact(date_req, "DD.MM.YYYY", CultureInfo.InvariantCulture );
// use this when you need to show that formatted date value
string formattedDate = dateValue.ToString("yyyy-MM-dd");
Better way is that use DateTime.TryParseExact Method, if you want it as date rather than string modify your culture info and date separator.
CultureInfo enUS = new CultureInfo("en-US");
string dateString;
DateTime dateValue;
dateString = "05.01.2009";
if (DateTime.TryParseExact(dateString, "DD.MM.YYYY", enUS,
DateTimeStyles.None, out dateValue))
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
dateValue.Kind);
else
Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
First parse it in the existing format then convert to the string format you want.
var date = DateTime.ParseExact(date_req, "dd.MM.yyyy", CultureInfo.InvariantCulture);
var str = date.ToString("yyyy-MM-dd");
You can first convert it to a character array. then you can parse day/month/year separately to integers . You know the indexes of the numbers so this will be easy. after that you can concatenate every element in the way you like.
Error. You have a cake and you want to eat a stake. In order to convince your stomach that that the cake is a stake you have to transform the cake to a stake. This cannot be done. Parsing is about accepting a value as it comes and use a pattern (or more) to translate it to something else and not transform it. So what you want may be right but you ask is wrong.

Retaining MM/DD/YYYY format in String

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.

How to convert a date which is given in CCYYMMDD format to MM/DD/CCYY using C#?

Can anyone help me to convert a date which is given in CCYYMMDD format to MM/DD/CCYY format in C#.
Assuming by "CC" you mean century, you should just parse it and reformat it:
DateTime date = DateTime.ParseExact("yyyyMMdd", text,
CultureInfo.InvariantCulture);
string newText = date.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);

Categories

Resources