I have a problem to convert string to date format in C#.
I'm getting the data through a row of a gridview:
string shipping_date = row["Shipping_Date"].ToString();
with format: 27/08/2015 00:00:00 but want convert to the format "yyyyMMdd".
Already used the method DateTime.TryParse, but without success...
After getting the date, it is to extract to a txt file (which I have to work). I've seen some identical issues here, but none worked for me.
Someone can help me convert to "yyyyMMdd"?
Thanks
Your question is not clear, I only guess you want something like this
var input = "27/08/2015 00:00:00";
var output = DateTime.ParseExact(input, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture)
.ToString("yyyyMMdd");
You can utilize the formatting in ToString(). You would simply do ToString(yyyyMMdd). That would use your formatting. The notations are:
Month: M (1), MM (02)
Day: d (1), dd (02)
Day of Week: ddd, dddd
Year: y (5), yy (15), yyy (015), yyyy (2015)
Hour: h (1), hh (02)
Minute: m (1), mm (02)
Second: s (1), ss (02)
There's a good chance the value is already a DateTime. Therefore, you should probably be doing this:
string shipping_date = String.Empty;
if(row["Shipping_Date"] != DBNull.Value)
shipping_date = ((DateTime)row["Shipping_Date"]).ToString("yyyyMMdd");
Related
I need to parse to following Date Aug 20 11:38:43 2017 GMT
I'm trying to use DateTime.TryParseExact but can't find the correct format.
my latest format is MMM dd hh:mm:ss yyyy
my code :
string nextUpdate; //Next Update: Aug 20 11:38:43 2017 GMT
string dateTimeFormat = "MMM dd hh:mm:ss yyyy";
DateTime crldt;
DateTime.TryParseExact(nextUpdate.Split(':')[1].Trim(), dateTimeFormat, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out crldt);
when I run the code I get crldt ~ Date = {1/1/01 12:00:00 AM}
my question : what format should I use or what alternative way can I use to parse this string to DateTime
UPDATE
using suggestions from : #Sergey Berezovskiy
I've updated the code to :
string nextUpdate; // Next Update: Oct 7 06:16:18 2017 GMT
string dateTimeFormat = #"MMM dd HH:mm:ss yyyy \G\M\T";
Regex r =new Regex(".*Next Update:.*");
nextUpdate = r.Match(Crltext).Value;
DateTime crldt;
DateTime.TryParseExact(nextUpdate.Substring(nextUpdate.IndexOf(':')+1).Trim(),
dateTimeFormat, System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AssumeUniversal, out crldt);
int intDTComp = DateTime.Compare(crldt, DT_now);
I've found a date that doesn't fit this format : Next Update: Oct 7 06:16:18 2017 GMT
what is the issue now ?
UPDATE 2
I've found the issue , but can't find a clean solution.
The issue is that the problematic date is Oct 7 ... ,
while the format is MMM dd ...
my workaround is adding another format MMM d hh:mm:ss yyyy and using it if date = {1/1/01 12:00:00 AM}
what other solution may I use in this scenario
First of all, don't forget that your string contains "GMT". You should either remove it from the string, or add to format pattern:
string nextUpdate = "Next Update: Aug 20 11:38:43 2017 GMT";
string format = #"MMM dd hh:mm:ss yyyy \G\M\T";
Next - don't split input string by : because there is another : symbols in the string. And you will get array with parts ["Next Update", " Aug 20 11", "38", "43 2017 GMT"]. Taking the second item from array gives you " Aug 20 11". Instead, you should just take substring after first : occurance:
string s = nextUpdate.Substring(nextUpdate.IndexOf(':') + 1).Trim();
And finally parse that string using your format:
IFormatProvider provider = CultureInfo.InvariantCulture;
DateTime date = DateTime.ParseExact(s, format, provider, DateTimeStyles.AssumeUniversal);
Output will depend on your time zone. E.g. for my time zone GMT+3 it will be:
8/20/2017 14:38:43
If this is your string:
"Next Update: Aug 20 11:38:43 2017 GMT"
Then when you do this:
nextUpdate.Split(':')[1].Trim()
You get this:
"Aug 20 11"
Which doesn't match your date format. I suspect you don't just want the second split value, but also all remaining split values. You can re-join them. Something like this:
string.Join(":", nextUpdate.Split(':').Skip(1)).Trim()
This would split them by the ":" character, skip the first one but keep all remaining ones, and re-join the remaining ones into another string with the ":" character again.
Note: You may also need to account for that time zone value. There are some helpful ideas on this question for how to do that.
If that's the input, I propose that you take the format exactly as the input
string nextUpdate = "Next Update: Aug 20 11:38:43 2017 GMT";
string dateTimeFormat = #"\N\e\x\t\ \U\p\d\a\t\e\:\ MMM dd hh:mm:ss yyyy\ \G\M\T";
DateTime crldt;
crldt = DateTime.ParseExact(nextUpdate, dateTimeFormat , System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
This way, when reading the code it's very clear what the expected format is, and you don't have code with Split() or other items that need explanation.
Also note that if you leave the colons (:) like that, they may be replaced by .NET to match the hour separator. Use \: if you always require a literal colon.
As I wrote in the comments before, note that you're ignoring the time zone.
Use following code
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime givenDate = DateTime.ParseExact("Aug 20 14:38:43 2017 GMT", "MMM dd HH:mm:ss yyyy GMT", provider); // here HH is for 24 hour format . use hh for 12 hour format
string expectedDate = givenDate.ToString("dd/MM/yy hh:mm:ss tt"); // tt is for AM or PM (no need to use tt if you use hour as HH I mean 24 hour format)
Your Output will be 20/08/17 11:38:43 AM
After reading some other similar questions and trying their suggestions, I'm still unable to get my time to parse into a DateTime-
string time1 = File.ReadAllText(#"C:\Reminders\Reminder1Time.txt");
DateTime dt1 = DateTime.ParseExact(time1, "hh:mm:tt", CultureInfo.InvariantCulture);
dateTimePicker1.Value = dt1;
time1 is a string value of 9:00 AM Other questions have mentioned to use ParseExact to specify a custom format, but it's still not parsing.
The error I get thrown is on the second line
String was not recognized as a valid DateTime.
How would I get the dateTimePicker1 to display the value from the time1 string?
Looks like a stray colon and an extra h if you are expecting a 12 hour clock 1-12 without a leading zero and the AM PM marker with whitespace.
Try: h:mm tt
All of the formatting options are buried in the documentation, here.
var datefromFile = File.ReadAllText(FILELOCATION);
var format = "dd-MM-yyy hh:mm:ss,fff";
var formattedDateTime = DateTime.ParseExact(dateFromFile, format, CultureInfo.InvariantCulture);
Make your format Explicit, remember dd for date capital MM for month and yyyy for year. hh for hour mm for minutes and ss for seconds.
MSDN Formats:
https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
There are several threads on similar topic with several solution but none of them are marked as answer.
I have a string and would like to convert into DateTime
string str = "12-3-2013 12-09-10 PM";
DateTime dt = DateTime.ParseExact(str, "MM-dd-yyyy HH-mm-ss tt", new CultureInfo("en-US"));
This gives an error. Is there something to do with CultureInfo? How does CultureInfo affect the output?
dd: The day of the month, from 01 through 31.
d: The day of the month, from 1 through 31.
For sure day is not dd as is using a single digit. Also, you need to change HH by hh or remove am/pm.
Try with this
MM-d-yyyy hh-mm-ss tt
You might need to change MM by M but it's impossible to say with provided example.
string str = "12-3-2013 12-09-10 PM";
Convert.ToDateTime(str);
I'm having problems with DateTime.ParseExact method which is throwing exceptions that my input string is not in correct format.
Code follows :
class Program
{
static void Main(string[] args)
{
var rawDate = "Thu, 08 nov 2012 15:19:18 0";
var _format = "ddd, dd MMM yyyy HH:mm:ss K";
var date = DateTime.ParseExact(rawDate, _format, CultureInfo.InvariantCulture);
}
}
I found a few similar threads here on SO with exact date format and nobody reports any problem there.
I followed this as my guide :
ddd = Three letter Day of week
MMM = Three letter month
dd = Two digit day of month 01-31 (use "d" for 1-31)
HH = Hours using 24-hour clock. 00-24 (use "H" for 0-24)
mm = Minutes. 00-59
ss = Seconds. 00-59
K = Time zone information
yyyy = 4-digit year
What can be cause of exceptions?
Thank you in advance!
I think your 'K' might be a bit off.
The link here might give an explanation: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx#KSpecifier
You can leave this blank and drop the 0 - K
You timezone is wrong in your input string - it needs to be in the format +00:00.
To test your datetime format strings, run them in reverse:
Console.WriteLine(DateTime.Now.ToString(_format));
which gives
Thu, 08 Nov 2012 15:50:58 +00:00
Time zone information looks like the most likely suspect to me.
Try this:
var _format = "ddd, dd MMM yyyy HH:mm:ss 0";
You will lose the timezone information, though.
I am trying to get date in this format
"yyyy MM dd"
with spaces between them not slashes, but its not working
using (SqlDataReader r = sqlComm.ExecuteReader())
{
if (r.Read())
{
DateTime Date
= Convert.ToDateTime((r["Date"]).ToString("yyyy/MM/dd"));
I can't make any change to SQL Stored Procedure at all
EDIT
Sorry it was giving me this for above "25 10 2012 10:00:00:00 AM" or something so I don;t think I was doing it properly, I only want date like this "yyyy MM dd"
how about changing \ into space?
.ToString("yyyy MM dd")
Building off of Marc's answer, it seems like you may be a bit confused about how the DateTime object vs. a string representation of the date actually work. The DateTime is just an offset from the starting point.
This line in your code first takes the value from the Date column in your SQL reader, then converts it to a string with the "yyyy/MM/DD" format, then finally turns that string into a DateTime object.
= Convert.ToDateTime((r["Date"]).ToString("yyyy/MM/dd"));
So as you can see, you're ending up with a DateTime object, not the display string you want. If you actually want this code to return just a formatted string , this is what your final line should look like:
EDIT
= r.GetDateTime(r.GetOrdinal("Date")).ToString("yyyy MM dd");
From date to string
var str= date.ToString("yyyy MM dd")
and for string to date
DateTime date = DateTime.ParseExact(string, "yyyy MM dd", CultureInfo.InvariantCulture);
So you want this format: "yyyy MM dd" but you use this "yyyy/MM/dd".
Instead:
String dateString = r.GetDateTime(r.GetOrdinal("Date")).ToString("yyyy MM dd");
look: http://ideone.com/XecnUP
A DateTime does not have a format. It is just the "how long since {epoch}", give-or-take some offset/timezone information. If the value in the source is a datetime, then all you need is:
DateTime date = (DateTime)r["Date"];
Then you might format that later at the UI. But to repeat: a DateTime does not have a format.