Set day and month format, but not their order - c#

I know about Datetime formats. "dd" stands for day from 01 to 31, "MM" - the month from 01 through 12. I need this format. But if I write "dd MM"(in my case in ToString() method) it will always put day before the month. How can I set this format(dd and MM) without changing the order(what comes first - day or month) from current locale? So if in current culture day comes first I want to receive "20 08 2012"(separator doesn't matter here), and if month comes first - "08 20 2012"

You can use the MonthDayPattern from the current locale to get the relative order of the two items, and then construct either dd MM or MM dd:
var mdp = CultureInfo.CurrentCulture.DateTimeFormat.MonthDayPattern;
string pattern = mdp.IndexOf('M') < mdp.IndexOf('d') ? "MM dd" : "dd MM";

Have a look at the culture's MonthDayPattern. Maybe you can customize it to your needs, e.g.
string FormatWithMonthDayPattern(DateTime dateTime, CultureInfo cultureInfo)
{
var pattern = cultureInfo.DateTimeFormat.MonthDayPattern;
return dateTime.ToString(Regex.Replace(pattern, "M+", "MM"));
}
var result1 = FormatWithMonthDayPattern(DateTime.Now, new CultureInfo("en-US"));
// result1 == "08 20"
var result2 = FormatWithMonthDayPattern(DateTime.Now, new CultureInfo("fr-FR"));
// result2 == "20 08"

Related

C# Parsing a long date

I have the following text that I am trying to parse into a date, but I can't seem to get the time zone correct.
Ideas?
Fri May 29 2015 00:00:00 GMT-0700 (Pacific Daylight Time)
(I can't change the date structure)
Try this:
string str = "Fri May 29 2015 00:00:00 GMT-0700 (Pacific Daylight Time)";
DateTime dt = new DateTime();
bool b = DateTime.TryParseExact(str.Substring(0,33), "ddd MMMM dd yyyy hh:mm:ss 'GMT'zzz", null, DateTimeStyles.None, out dt);
This makes the assumption that the description of the time zone is irrelevant since the offset from GMT is given. Therefore, parsing the substring of the original date string only upto the timezone offset part should be sufficient.
Demo
there is a shortcut way that I sometimes use.
first split the string based on space like:
var dateString = 'Fri May 29 2015 00:00:00 GMT-0700 (Pacific Daylight Time)';
var dateArray = stdateString.Split(' ');
second we need time. for that
var timeString = dateArray[4];
var timeArray = timeString.Split(':');
third for timezone
var timezoneString = dateArray[5];
var timezoneSignPart = timezoneString.Substring(3,1)
var timezoneHourPart = timezoneString.Substring(4,2)
var timezoneMinPart = timezoneString.Substring(6,2)
After that you may use to construct the date however you want to like
This is very personal way for me when I don't have much time to investigate what is the problem ob the coming date strings.

regular expression using C# to find a date

I try to use regular expression to find a date and time from a log file that looks like this:
Dec 25 14:11:03....
what is the best way to find them in log file and calculate the date and time
to an absolute value?
I am trying this code but it doesn't find the expression:
public long getDateAndgetTimeFromLog(TypeOfProtocols type, string lineOfLog)
{
long dnt = 0; //variable from date and time.
switch (type)
{
case TypeOfProtocols.PlinkSnifer:
if (Regex.IsMatch(lineOfLog, #"\d{2}:\d{2}:d{2}"))
{
}
break;
}
return dnt;
}
First: your pattern is invalid:
#"\d{2}:\d{2}:d{2}"
it must be:
#"\d{2}:\d{2}:\d{2}"
you missed one backslash \ before the last d
Second: I guess by absolute value you mean the long dnt variable? If so then you need to parse the date by using one of the overloads and get the DateTime.Ticks.
For example like this:
string dateString = "Dec 25 14:11:03";
DateTime date = DateTime.ParseExact(dateString, "MMM dd HH:mm:ss", CultureInfo.InvariantCulture);
long ticks = date.Ticks;
where:
MMM The abbreviated name of the month.
dd The day of the month, from 01 through 31.
HH The hour, using a 24-hour clock from 00 to 23.
mm The minute, from 00 through 59.
ss The second, from 00 through 59.
Custom Date and Time Format Strings
Third: your current pattern cannot find and capture the entire timestamp so you'll need to extend it to get the date and time parts in one string:
string logLine = "Dec 25 14:11:03 Hello world!";
// Your new pattern:
string pattern = #"([a-z]{3} \d{2} \d{2}:\d{2}:\d{2})";
Match match = Regex.Match(logLine, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
string dateFormat = "MMM dd HH:mm:ss";
string dateString = match.Groups[1].Value;
DateTime date = DateTime.ParseExact(dateString, dateFormat, CultureInfo.InvariantCulture);
long ticks = date.Ticks;
}
Currently you are only checking whether a log line contains a timestamp. I've added a () catching group to the pattern so you can use the cought value match.Groups[1].Value for parsing if a match was found. The index is 1 because there is only one group defined in the pattern. Group at the index 0 always contains the original string (the entire log line in this case).

C# DateTime ParseExact exception

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.

Convert weird date format to short DateTime

I have a date string, returned from a ExtJS datetime picker, which looks like this:
Wed Apr 25 2012 00:00:00 GMT+0300 (GTB Daylight Time)
From this I would need to have it in this format : YYYY-mm-dd, using C# or JavaScript.
How could I do this? I've tried using DateTime.Parse and it cannot be parsed.
Any idea?
You don't seem to care about the time and timezone information so you can in fact use DateTime.ParseExact to parse the date. Assuming that the day of month part may be just a single digit (e.g. 2012-04-01 is Sun Apr 1 2012) the pattern you need to use is ddd MMM d yyyy.
The "hardest" part is really chopping of the time and timezone part. If the day of month is a single digit you have to take of substring of length 14; otherwise of length 15. Here is a way to get the index of the 4th space character in a string:
var str = "Wed Apr 25 2012 00:00:00 GMT+0300 (GTB Daylight Time)";
var index = -1;
for (var i = 0; i < 4; i += 1)
index = str.IndexOf(' ', index + 1);
You can then parse the date into a DateTime:
var date = DateTime
.ParseExact(str.Substring(0, index), "ddd MMM d yyyy", CultureInfo.InvariantCulture);
This can be formatted back into a string using whatever format and culture you need.
In .NET, where you have a string representation of a date that has a guaranteed format, you can use DateTime.ParseExact to parse it:
var input = "Wed Apr 25 2012 00:00:00 GMT+0300 (GTB Daylight Time)"
.Substring(0, 15);
var format = "ddd MMM dd YYYY";
var date = DateTime.ParseExact(input, format, CultureInfo.InvariantCulture);
// Now date is a DateTime holding the date
var output = date.ToString("yyyy-MM-dd");
// Now output is 2012-04-25
May be this can help you Click
try this using Javascript.
var d = new Date('Wed Apr 25 2012 00:00:00 GMT+0300 (GTB Daylight Time)');
var curr_day = d.getDate();
var curr_month = ('0'+(d.getMonth()+1)).slice(-2)
var curr_year = d.getFullYear();
var new_date = curr_year+"-"+curr_month+"-"+curr_day;
In JavaScript
new Date("Wed Apr 25 2012 00:00:00 GMT+0300 (GTB Daylight Time)")
Will give you a date object. You can then format it to your date format (or preferably ISO8601, or milliseconds from the epoc using .getTime()) by picking out the (UTC) year, month and day

How can I get this DateTime format in .NET

I'm trying to format some DateTime into this W3C DateTime format :-
Complete date plus hours and minutes:
eg. YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
where:
YYYY = four-digit year
MM = two-digit month (01=January, etc.)
DD = two-digit day of month (01 through 31)
hh = two digits of hour (00 through 23) (am/pm NOT allowed)
mm = two digits of minute (00 through 59)
ss = two digits of second (00 through 59)
s = one or more digits representing a decimal fraction of a second
TZD = time zone designator (Z or +hh:mm or -hh:mm)
I originally had this...
var myDateTime = someDateTime.ToString("s",
System.Globalization.CultureInfo.InvariantCulture);
But that results in a string of :
2011-08-31T08:46:00
Can anyone help?
You want "o":
var myDateTime = someDateTime.ToString("o",
System.Globalization.CultureInfo.InvariantCulture);
Use the following:
yourDateTime.ToString( "yyyy-MM-ddTHH:mmK", CultureInfo.InvariantCulture );
Here is more than you'll ever want to know on DateTime formats:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
I believe you want
"yyyy-MM-ddTHH:mmK"
Note:
HH rather than hh to be 24 hour
K to specify the time zone; this relies on the DateTime.Kind being UTC or local; unspecified will end up with an empty string
You should also use CultureInfo.InvariantCulture to make sure no funky culture information is used. (You could quote the - and : as an alternative, but I'd use the invariant culture to make sure.)
You can format it like this:
someDateTime.ToString("yyyy-MM-dd");
Here's the documentation of the 'standard' supported datetime format strings:
http://msdn.microsoft.com/en-us/library/az4se3k1(v=VS.100).aspx
someDateTime.ToUniversalTime().ToString("u");
Will get you pretty close => '2011-09-02 10:22:48Z'. If that isn't good enough, then you can create a custom format string that includes the "T" (see 'Custom Date and Time Format Strings').

Categories