I am working with DateTime, trying to get date in the format like this:
03.05.2010-04.05.23 that is: dd.MM.yyyy-HH.mm.ss
I'm using DateTime.ParseExact to try to achieve this (maybe wrong)
So far I have:
var dateInFormat = DateTime.ParseExact(DateTime.Now.ToShortDateString(), "dd.MM.yyyy.HH.mm.ss", null);
But can't quite get exactly what I want. Basically I want to keep the 0, for example time is 05:03:20 PM I don't want it to show like 5:3:20 PM
Any ideas?
If you have a date as DateTime (not string) then you can format it as leppie indicates:
string date = DateTime.Now.ToString("dd.MM.yyyy-HH.mm.ss");
If on the other hand you have a date as string in the format dd.MM.yyyy-HH.mm.ss then you can use
string mydate = "03.05.2010-04.05.23";
DateTime dateFromString = DateTime.ParseExact(mydate, "dd.MM.yyyy-HH.mm.ss", null);
you get the exception because your string has the wrong format (namely the systems short date format)-
Is there any problem just using ToString()? Eg:
Console.WriteLine(dateInFormat.ToString("dd.MM.yyyy-HH.mm.ss"));
Related
I am trying to get the created date and time of a particular file and then format it from 4/9/2016 to 040916. I end up with the result of 56DD16. I am not entirely sure where this value is coming from. I have used this method to format dates before without any problem. The code is below:
FileInfo fi = new FileInfo(Path.Combine(r.getCompanyFilesLocation(), r.getNyseFileName()));
DateTime dateCreated = fi.CreationTime;
string archiveFileName = dateCreated.ToString("mmDDyy");
You are using incorrect format string,mm Represent the Minute and there is nothing for DD, dd stands for day. so Change your formatString as MMddyy. to get the expected output. Here you can find more formatting options
string archiveFileName = dateCreated.ToString("MMddyy");
.ToString("mmDDyy") is incorrect. The format should be .ToString("MMddyy")
You can always review the Custom Date and Time Format Strings.
You were using wrong format. Use this one and you will get the exact same output you required:
DateTime dateCreated = fi.CreationTime;
string archiveFileName = dateCreated.ToString("MMddyy", CultureInfo.InvariantCulture);
I am trying to convert the DateTime to following Format.
2015-06-11 07:14:03.930
I have tried with ,
string plannedStartTime = startTime.ToString("o");
output:2015-06-12T16:54:47.3206929+05:30
and
string plannedStartTime = startTime.ToString("u");
output:2015-06-12 16:56:57Z
Not getting any formatters from MSDN
Any other Formatters?
all you need is a right format string
try using this startTime.ToString("yyyy-MM-dd HH:mm:ss.fff")
There is no standard date and time format for your output. You need to use custom date and time format specifiers with a culture that have : as a TimeSeparator like InvariantCulture;
string plannedStartTime = startTime.ToString("yyyy-MM-dd HH:mm:ss.fff",
CultureInfo.InvariantCulture);
If your CurrentCulture already have : as a TimeSeparator, you don't need to pass second parameter in ToString method.
Hope this is what your asking for
string plannedStartTime = startTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
I got a problem when trying to convert a date-time format with SAP RFC.
I'm trying this:
string tmpDate = argDate.ToString("dd.MM.yyyy");
DateTime date = Convert.ToDateTime(tmpDate);
IRfcFunction SAPRateAPI = null;
SAPRateAPI = _ecc.Repository.CreateFunction("ZRFC_CUST_CONDITION_RATE");
SAPRateAPI = CreateSAPRateAPI(SAPRateAPI, argPartnerSAPTranCode, argCustSAPTranCode, argMaterialCode, date);
SAPRateAPI.Invoke(_ecc);
But getting an error 'Specified Cast is not valid'
DateTime in C# has its own representation and doesn't has any "format" which you can see or change.
So phrase "datetime in dd.mm.yyyy format" has no sense at all.
Let's look at your code:
string tmpDate = argDate.ToString("dd.MM.yyyy");
DateTime date = Convert.ToDateTime(tmpDate);
Here you're converting DateTime to string and then back to DateTime.
You're getting exception on back cast just because Convert uses your windows specified culture, and in the case it differs from the one in the string - you need DateTime.ParseExact and explicit format specification.
But even if this cast will be successful - you again will get DateTime and this two lines will not change its format.
It looks like all you need - is just pass date only part of datetime as argument of your function. But it can be achieved pretty easily without any casts just by using argDate.Date (assuming agrDate is DateTime)
DateTime date = new DateTime( argDate.Years, argDate.Month, argDate.Day );
I think this is what you want.
See: C# Reference
Edit:
Which is the same as Andy Korneyev solution - Ok, his is nicer too look at, but both create a second DateTime object.
Consider using the DateTime.ParseExact method.
// Parse date and time with custom specifier.
string format = "dd.mm.yyyy hh:mm:tt";
DateTime date;
try {
date = DateTime.ParseExact(argDate, format, CultureInfo.InvariantCulture);
}
catch (FormatException e) {
throw new ArgumentException("argDate", e);
}
I have tried out as many suggestions as I've found on Stackoverflow, but not getting the desired result. Any help would be much appreciated.
My date string is "04-Dec-2013 14:14:02.143" and I want to convert this exactly as into DateTime format.
This was the last suggestion I tried:
String MyString;
MyString = "04-Dec-2013 14:14:02.143";
DateTime MyDateTime;
MyDateTime = new DateTime();
MyDateTime = DateTime.ParseExact(MyString, "dd-MMM-yyyy HH:mm:ss.fff",
null);
However, I keep getting the undesired result of "04/12/2013 14:14:02" rather want it to be "04-Dec-2013 14:14:02.143".
Any suggestions?
Yes, you should read about DateTime struct. It has not have any format info attached, it's just a plain number representing point in time.
The format come into play when you try to get string representation of the data, using ToString(format) method.
Use the format string every time you're calling ToString to get the date in the format you want it to be:
var stringDateRespresentation = dateValue.ToString("dd-MMM-yyyy HH:mm:ss.fff");
To make things easier you should pass plain, non-formatted DateTime instances all around and change it into string using ToString method only when it's being presented to the user.
#MarcinJuraszek has better answer on this question, but it does not solve the problem of different datetime patterns, because of what great SO users mark other questions as duplicate.
string MyString = "Dec-12-2013 14:14:02.143";
CultureInfo ukCulture = new CultureInfo("en-GB");
ukCulture.DateTimeFormat.ShortDatePattern = "MMM-dd-yyyy HH:mm:ss.fff";
DateTime myDateTime = DateTime.Parse(MyString, ukCulture.DateTimeFormat);
string QbDate = myDateTime.ToString("dd-MMM-yyyy HH:mm:ss.fff");
To solve the issue of different date-time patterns override any date pattern of any culture
As mentioned by #MarcinJuraszek the format comes into picture when you convert it back to string. The format you mentioned in ParseExact is for the parsing. i.e. How will MyString be parsed to create a DateTime object.
See below example just so you understand how the ParseExact format string is used.
If you use MyDateTime.ToString("dd-MMM-yyyy HH:ss:mm.fff"); instead (see I swapped mm and ss) in ParseExact you will get "12/4/2013 2:02:14 PM" instead of "12/4/2013 2:14:02 PM"
I am trying to convert my string formatted value to date type with format dd/MM/yyyy.
this.Text="22/11/2009";
DateTime date = DateTime.Parse(this.Text);
What is the problem ?
It has a second override which asks for IFormatProvider. What is this? Do I need to pass this also? If Yes how to use it for this case?
Edit
What are the differences between Parse and ParseExact?
Edit 2
Both answers of Slaks and Sam are working for me, currently user is giving the input but this will be assured by me that they are valid by using maskTextbox.
Which answer is better considering all aspects like type saftey, performance or something you feel like
Use DateTime.ParseExact.
this.Text="22/11/2009";
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);
You need to call ParseExact, which parses a date that exactly matches a format that you supply.
For example:
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
The IFormatProvider parameter specifies the culture to use to parse the date.
Unless your string comes from the user, you should pass CultureInfo.InvariantCulture.
If the string does come from the user, you should pass CultureInfo.CurrentCulture, which will use the settings that the user specified in Regional Options in Control Panel.
Parsing a string representation of a DateTime is a tricky thing because different cultures have different date formats. .Net is aware of these date formats and pulls them from your current culture (System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat) when you call DateTime.Parse(this.Text);
For example, the string "22/11/2009" does not match the ShortDatePattern for the United States (en-US) but it does match for France (fr-FR).
Now, you can either call DateTime.ParseExact and pass in the exact format string that you're expecting, or you can pass in an appropriate culture to DateTime.Parse to parse the date.
For example, this will parse your date correctly:
DateTime.Parse( "22/11/2009", CultureInfo.CreateSpecificCulture("fr-FR") );
Of course, you shouldn't just randomly pick France, but something appropriate to your needs.
What you need to figure out is what System.Threading.Thread.CurrentThread.CurrentCulture is set to, and if/why it differs from what you expect.
Although the above solutions are effective, you can also modify the webconfig file with the following...
<configuration>
<system.web>
<globalization culture="en-GB"/>
</system.web>
</configuration>
Ref : Datetime format different on local machine compared to production machine
You might need to specify the culture for that specific date format as in:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); //dd/MM/yyyy
this.Text="22/11/2009";
DateTime date = DateTime.Parse(this.Text);
For more details go here:
http://msdn.microsoft.com/en-us/library/5hh873ya.aspx
Based on this reference, the next approach worked for me:
// e.g. format = "dd/MM/yyyy", dateString = "10/07/2017"
var formatInfo = new DateTimeFormatInfo()
{
ShortDatePattern = format
};
date = Convert.ToDateTime(dateString, formatInfo);
After spending lot of time I have solved the problem
string strDate = PreocessDate(data);
string[] dateString = strDate.Split('/');
DateTime enter_date = Convert.ToDateTime(dateString[1]+"/"+dateString[0]+"/"+dateString[2]);
private DateTime ConvertToDateTime(string strDateTime)
{
DateTime dtFinaldate; string sDateTime;
try { dtFinaldate = Convert.ToDateTime(strDateTime); }
catch (Exception e)
{
string[] sDate = strDateTime.Split('/');
sDateTime = sDate[1] + '/' + sDate[0] + '/' + sDate[2];
dtFinaldate = Convert.ToDateTime(sDateTime);
}
return dtFinaldate;
}
use this to convert string to datetime:
Datetime DT = DateTime.ParseExact(STRDATE,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat)
Just like someone above said you can send it as a string parameter but it must have this format: '20130121' for example and you can convert it to that format taking it directly from the control. So you'll get it for example from a textbox like:
date = datetextbox.text; // date is going to be something like: "2013-01-21 12:00:00am"
to convert it to: '20130121' you use:
date = date.Substring(6, 4) + date.Substring(3, 2) + date.Substring(0, 2);
so that SQL can convert it and put it into your database.
Worked for me below code:
DateTime date = DateTime.Parse(this.Text, CultureInfo.CreateSpecificCulture("fr-FR"));
Namespace
using System.Globalization;
You can use also
this.Text = "22112009";
DateTime newDateTime = new DateTime(Convert.ToInt32(this.Text.Substring(4, 4)), // Year
Convert.ToInt32(this.Text.Substring(2,2)), // Month
Convert.ToInt32(this.Text.Substring(0,2)));// Day
Also I noticed sometimes if your string has empty space in front or end or any other junk char attached in DateTime value then also we get this error message