I am using JsonConverter attribute to set my datetime format but for the string
"yyyyMMddThhmmss.000GMT" I get dates like "19900321T20000.000G3T" because of the latter M. How do I escape these characters in my format string?
You can use:
"yyyyMMdd'T'HHmmss'.000GMT'"
I changed hh to HH since most (sane) people use a 24-hour count.
On the documentation Custom Date and Time Format Strings it is shown that aopstrophe characters like in 'string' can be used for literal string delimiters. Now I also put the T inside this delimiter, just for clarity, even if one capital T has no other meaning in a DateTime format string.
Use single quote to escape like:
"yyyyMMddThhmmss'.000GMT'"
Like:
string str = "19900321T20000.000GMT";
DateTime dt = DateTime.ParseExact(str,"yyyyMMddTHHmms'.000GMT'", CultureInfo.InvariantCulture);
Change hh to HH for 24 hours, also it appears your seconds are single digit values, so use a single s.
(I assume in your question original string you have GMT, not G3T)
You have 2 options to use your ...GMT part as string literal delimiter in custom date and format string:
".000GMT"
'.000GMT'
But I suggest to use single quotes because if you use double quotes, you need to escape your quotes with \ (because of escape sequence) or you can use verbatim string literal.
Do the same thing with T middle in your string as well.
Also use HH specifier which is for 24-hour clock and use s speficier instead of ss because you have 5 digit after your T that's why it doesn't accept HHmmss format.
The reason of you get G3T it is because M is has meaning of month of custom string format and that's why your GMT parsed as G3T.
string s = "19900321T20000.000G3T";
var dt = DateTime.ParseExact(s, "yyyyMMdd'T'HHmms'.000G3T'",
CultureInfo.InvariantCulture);
With double quotes;
string s = "19900321T20000.000G3T";
var dt = DateTime.ParseExact(s, "yyyyMMdd\"T\"HHmms\".000G3T\"",
CultureInfo.InvariantCulture);
Related
string date = "17:25";
if(date.Lenght == 5){
myobj.StartTime = DateTime.ParseExact(date, "HH:mm", CultureInfo.InvariantCulture);
// add only hh and minutes and preserve day and year
}
else if(date.Lenght > 5){
myobj.StartTime = DateTime.ParseExact(date, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
}
myobj.StartTime is obviously of DateTime datatype.
I know I could break this string on : and use first part as hours and then convert that to double and then use AddHours, and I should repeat that for minutes also but I'm wonder is there convenient way to do this?
You can use TimeSpan.ParseExact:
myobj.StartTime = myobj.StartTime.Add(TimeSpan.ParseExact(date, "hh\\:mm", CultureInfo.InvariantCulture));
In hh\\:mm hh are hours (you cannot use HH here, not supported by this concrete method), mm are minutes, and \\: is escaped : character. One slash is to escape slash itself in C# literal string (otherwise you can do this: #"hh\:mm"), and you need to escape : with slash in format string, because otherwise TimeSpan.ParseExact will treat it as custom format specifier (like h), but there is no such format specifier and it will throw invalid format exception.
Note that if you also allow single-digit hours and minutes (like this: "1:2" or "1:25") - then you have to use another format:
TimeSpan.ParseExact(date, #"h\:m", CultureInfo.InvariantCulture);
This format will handle both single-digit and two-digit hours and minutes.
Also note that if you have more than 24 hours in your string (like "25:11") - this method will not work and you will have to fallback to split (as far as I know).
I am trying to format date entered by user.
Dates are provided in the following format:
d/M/yyyy (ie: 1/1/2012, but could be also 12/1/2012 or 1/12/2012)
however I need them converted to:
dd/MM/yyyy (ie: 01/01/2012)
I managed to do it in non-Regex way, like this:
string date = "1/1/2012";
if (date.IndexOf("/") == 1)
{
date = "0" + date;
}
if (date.Substring(4, 1) == "/")
{
date = date.Insert(3, "0");
}
I would really like to know how to do it with Regex.Replace, however, as it would probably be neater.
I tired different variations of the below:
string date = "1/1/2012"
date = Regex.Replace(date, #"\d{1}/", "0$&");
The above will work, but if the date is 12/1/2012, it will also make 102 out of 12. If I add ^ at the beginning of pattern I don't get the second number changed. I also tried combinations with [^|/] at the beginning, but also no luck. So at the moment it is either or.
Use word boundary \b which matches between a word character and a non-word character.
date = Regex.Replace(date, #"\b\d/", "0$&");
OR
date = Regex.Replace(date, #"\b(\d)/", "0$1/");
DEMO
If you're sure of the incoming format, I'd use DateTime.ParseExact instead, then use .ToString() to reformat the date:
DateTime dt = DateTime.ParseExact(input, "d/M/yyyy", CultureInfo.CurrentCulture);
string reformatted = dt.ToString("dd/MM/yyyy");
I have a string. The string is like this
Hello I am a Coder, My DOB is 12/09/2011.
I want to extract the date from this sentence. How do I do this using C#? I do not want regular expressions. This was an interview question asked to me recently.
This is my try
string myStr = "Hello 12/3/2013";
DateTime s;
DateTime.TryParse(myStr,out s);
Console.WriteLine(s);
I am getting the output as
01-01-0001 00:00:00
Both C# and JavaScript support regular expressions. You can use this pattern to find that section of the string:
\d{2}/\d{2}/\d{4}
Of course that doesn't ensure that it's a valid date, e.g. 13/88/0000 would match that pattern. You'd then have to parse the string using something like Date.Parse.
However, since you've stated regular expressions are not an option, here's a very crude one-liner:
var input = "Hello I am a Coder, My DOB is 12/09/2011.";
DateTime date = new DateTime();
input.Split().SkipWhile(s => !DateTime.TryParse(s, out date)).Any();
Console.WriteLine(date); // 12/9/2011 12:00:00 AM
Since you don't want to use REGEX, simply split the string on space and then use DateTime.TryParseExact to see if any string gets parsed as DateTime
string str = "Hello I am a Coder, My DOB is 12/09/2011";
string[] array = str.Split();//splits on space
string dateFormat = "M/d/yyyy"; //works with both single digit and double digit
//(day/month) for parsing
//or d/M/yyyy depending your date culture
DateTime tempDateTime;
var result = array.FirstOrDefault(r =>
DateTime.TryParseExact
(r,
dateFormat,
CultureInfo.InvariantCulture,
DateTimeStyles.NoCurrentDateDefault,
out tempDateTime));
Your result would contain the Date string, and your tempDateTime would contain the parsed DateTime.
I want to convert date format from dd-mmm-yyyy (16-May-2013)
to date format mm/dd/yyyy (09/12/2013).
I am using this code. But still not able to get the correct value. the month value is becoming zero.
string dt = DateTime.Parse(txtVADate.Text.Trim()).ToString("mm/dd/yyyy");
In the above code txtVADate is the TextBox Control Which is giving date format
like
dd-mmm-yyyy example (16-May-2013).
Any Answers are appreciable.
The format specifier for month is MM not mm, try using MM/dd/yyyy. Also when using a custom format it's best to pass InvariantCulture to avoid any clashes with the current culture your app is running under i.e.
DateTime.Parse(txtVADate.Text.Trim()).ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
See Custom Date and Time Format Strings.
Use capital M letter.
m - minute
M - month
You have to use MM instead of mm and CultureInfo.InvariantCulture as second parameter
string dt = DateTime.Parse(txtVADate.Text.Trim()).ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
The slashes / mean: "replace me with the actual current date-separator of your culture-info".
To enforce / as separator you can use CultureInfo.InvariantCulture:
string dt = DateTime.Parse(txtVADate.Text.Trim())
.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
MSDN:
/
The date separator defined in the current
System.Globalization.DateTimeFormatInfo.DateSeparator property that is
used to differentiate years, months, and days.
( you also have to use MM instead of mm since lower case is minute whereas uppercase is month )
string dt = datatime.toshortdatestring`
Here is your solution.
using System.Globalization;
string dt = DateTime.Parse(txtDate.Text.Trim()).ToString("mm/dd/yyyy", CultureInfo.InvariantCulture);
also can be done like this
public string FormatPostingDate(string txtdate)
{
if (txtdate != null && txtdate != string.Empty)
{
DateTime postingDate = Convert.ToDateTime(txtdate);
return string.Format("{0:mm/dd/yyyy}", postingDate);
}
return string.Empty;
}
I get a string from Excel as so: "\"11/01/2011 16:00\""
What's the most efficient way to trim this in C# so it can be parsed as a DateTime?
You could probably just trim the string, not sure how consistent that format will be though
var trimmedString = excelString.Trim('\\', '"');
That's assuming the string contains the slashes and those speech marks. If it's just the speech marks (because visual studio has escaped the string when displaying it) then all you need is
var trimmedString = excelString.Trim('"');
You don't need to trim it at all - you can just call DateTime.ParseExact or DateTime.TryParseExact which contains the quotes at each end:
string text = ...;
DateTime date = DateTime.ParseExact(text, "'\"'dd/MM/yyyy HH:mm'\"'",
CultureInfo.InvariantCulture);
I don't know whether that's more efficient than trimming (there's more parsing, but no extra string to create) but I would use it for its precision: if ever the data form changes (e.g. there's no longer a quote) you'll find out because you're stating your expectations, effectively.
string myString = "\"11/01/2011 16:00\"";
DateTime time = DateTime.Parse(myString.Substring(1, myString.Length - 2));
Always in that format? Can't you just substring the first 3 and last 3 characters and then Parse to a Date with a specific (supplied) date format?
s = s.Substring(1, s.Length-2);
You're looking for the parseExact method.
char[] trimChars = {'\"'};
string dateTime = "\"11/01/2011 16:00\"".Trim(trimChars);
DateTime result = DateTime.ParseExact(dateTime, "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);