Convert a specific format dateTime string to DateTime in C# - c#

I have a formatted datetime string and I want to convert it back to DateTime but when I parse or convert that string to DateTime it throws exceptio that string is not a valid dateTime.
Here is how DateTime string is created
string temp = dt.Year.ToString("D4") +
dt.Month.ToString("D2") +
dt.Day.ToString("D2") +
dt.Hour.ToString("D2") +
dt.Minute.ToString("D2") +
dt.Second.ToString("D2");
and here is how i am parsing it back to DateTime
DateTime dtchk = DateTime.Parse(temp);

Yes it is but this is happening in a different module.
I don't even understand what is that mean. I think you just need;
DateTime dtchk = dt;
Nothing more. But anyway.. I try to explain;
Since "D" format specifier generates string representation with leading zeros if your string length is less than precision specifier, your temp will be the combination of these wider formats of months, day, hour etc..
And DateTime.Parse parses your string successfully if this string is a standard date and time format of your CurrentCulture. In your case, it is not.
You need to parse your string with ParseExact to specify your formats exactly.
DateTime dtchk = DateTime.ParseExact(temp, "yyyyMMddHHmmss", null);

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

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.

Unable to convert textbox(dd/MM/yyyy) date to datetime format

I have a database date "2014-11-26". I have a calender with format(dd-MM-yyyy) I am trying to bring some values to my form from databse by textbox selected date
protected void txtdate_TextChanged(object sender, EventArgs e)
{
//DateTime timeIn = Convert.ToDateTime(txtdate.Text);
// DateTime time1 = DateTime.ParseExact(txtdate.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
str = "select TimeIn,TimeOut from MusterRoll where EmpCode='" + ddcode.SelectedItem.Text + "' and Date='"+time1+"'";
dr = conn.query(str);
if (dr.Read())
{
DateTime time = dr.GetDateTime(0);
TimeSelector1.SetTime(time.Hour, time.Minute, TimeSelector1.AmPm);
DateTime time2 = dr.GetDateTime(1);
TimeSelector2.SetTime(time2.Hour, time2.Minute, TimeSelector2.AmPm);
}
}
The problem is databse date format and my calender format is different. I tried two methods(which I placed in command line)but shows error message like "input string was not in correct format". I surfed internet and find these same answers. May I know why it shows error?? i am trying to make database dateformat and calender format as same
First of all, a DateTime doesn't have any implicit format. It has just date and time values. String representations of them can have a format.
I strongly suspect you save your DateTime values with their string representations which is a horrible idea. Read: Bad habits to kick : choosing the wrong data type Pass your DateTime values directly to your parameterized queries instead of their string representations. Anyway..
For;
DateTime timeIn = Convert.ToDateTime(txtdate.Text);
Convert.ToDateTime(string) method uses DateTime.Parse method with your CurrentCulture settings. That means if your string isn't a standard date and time format of your CurrentCulture your code throws FormatException. I guess dd-MM-yyyy is not a standard date and time format of your CurrentCulture.
For;
DateTime time1 = DateTime.ParseExact(txtdate.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
When you use DateTime.ParseExact, your string and format should match exactly.
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.
In your case; they are not ("26-11-2014" and "yyyy-MM-dd"). Use dd-MM-yyyy format instead.
DateTime time1 = DateTime.ParseExact(txtdate.Text,
"dd-MM-yyyy",
CultureInfo.InvariantCulture);
Then you can generate the format from your time1 like;
time1.ToString("yyyy-MM-dd"); // A string formatted as 2014-11-26
For your command part, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
You can use this
var dateAndTime=Convert.ToDateTime(Txttradedate.Text).ToString("ddmmyyyy");

.NET convert Datetime to format Sortable date/time pattern ("s");

Im working with VS2008, .NET and C#, and I need to send to one of our clients a DATETIME variable.
The problem is that they want the Date in the format Sortable date/time pattern ("s").
When I get the actual datetime, it is a Datetime object. When I format it to the given format is now a String object, and it has the format I want. But after that I can't create a Datetime object from that formatted String with the same format, because it always returns it to the original Datetime format.
More specific:
DateTime currTime = System.DateTime.Now; //(the format is "13/08/2010 09:33:57 a.m.")
String date = String.Format("{0:s}", currTime);// (wanted format "2010-08-13T09:33:57")
DateTime newDate = DateTime.Parse(date);// (original format again "13/08/2010 09:33:57 a.m.")
IFormatProvider culture = new System.Globalization.CultureInfo("", true); //(Invariant Culture)
String format = "s";
DateTime fecha = DateTime.ParseExact(date, format, culture); // (original format again "13/08/2010 09:33:57 a.m.")
Is there a way of getting a Datetime object with the desired format, or Datetime objects use a given format, and you can't format them to the equivalent string formats?
Thx
A DateTime is just a number. It has no intrinsic "format". It is only rendered into a format when converted to a string. Hence, whenever you need a DateTime as a string, you have to specify what format you want it in.
String date = String.Format("{0:s}", currTime);
This can be shorted a bit to :
String date = currTime.ToString("s");
If I understand the question correctly, I think you are getting confused. A DateTime object itself is not formattable, it is essentialy just a numeric value (number of ticks since DateTime.MinValue or whatever it is).
You can convert a DateTime object into a string representation in whatever format you like, but you aren't changing the actual DateTime object.
Every time you use a DateTime value in a place where it needs to be turned into a string (e.g. in string.Format()), C# will generally call the .ToString() method. The DateTime type declares a .ToString() method that has the format you don’t want.
However, DateTime has additional methods, including .ToString(IFormatProvider provider) and .ToString(string format).
Therefore, you can probably achieve what you want if you replace every use of a DateTime variable in the relevant string-like context to one that calls the appropriate .ToString overload, for example:
Instead of
var message = string.Format("The parcel was sent on {0}.", currTime);
use
var message = string.Format("The parcel was sent on {0}.", currTime.ToString("s"));

Categories

Resources