I have written the below query to create an xml from entity, I need to get date time in .NET in yyyymmddhhmmss format for the field SLOTTINGTIME, so I have thought of writing a new method to get date time in desired format.
var slottingmessagexml = new XDocument(new XElement("Message",
new XAttribute("ID","SLT"),
new XElement("Record",
new XAttribute("STORENO",slottingmessage.StoreID),
new XAttribute("PICKLOCATION",slottingmessage.PickLocation),
new XAttribute("TPNB",slottingmessage.ProductID),
new XAttribute("SLOTTINGTIME",GetDateTimeInNewFormat(slottingmessage.SlottingDateTime)),
new XAttribute("SLOTTTINGACTION",slottingmessage.SlottingAction))
)
);
You can use
string strDate = DateTime.Now.ToString("yyyyMMddhhmmss");
If 24hr format is required that use uppercase HH inplace of hh in the format string.
Remember the first MM should be in upper case as lower case mm is for minutes where as uppercase is for Month.
For your particular case instead of writing a new method you can do:
new XAttribute("SLOTTINGTIME",slottingmessage.SlottingDateTime.ToString("yyyyMMddhhmmss")),
One more thing to add: The output will contain Hour in 12 hours format because of the lower case hh part in the string. Not really sure if you need that because without AM/PM this can't indicate the accurate time. For that purpose use HH for hours which will display hours in 24 hour format. So your code could be:
new XAttribute("SLOTTINGTIME",slottingmessage.SlottingDateTime.ToString("yyyyMMddHHmmss")),
//^^ for 24 hours format
How about this?
public string GetDateTimeInNewFormat(DateTime d)
{
return d.ToString("yyyyMMddhhmmss");
}
Or, for 24h format:
public string GetDateTimeInNewFormat(DateTime d)
{
return d.ToString("yyyyMMddHHmmss");
}
Although your question does not explicitly say what format you are looking for, I think that based on your example format of yyyymmddhhmmss we can assume that you want [years][months][days][hours][minutes][seconds].
Based on that, we can break each part down as follows:
Years: If you want the full year then your yyyy is correct and will prduce 2013 for example. A common (although not encouraged) alternative could be yy (e.g. 13)
Months: Currently your attempt of mm does not return months. It will produce the minutes. You likely want MM (e.g. 04). Alternative include MMM (e.g. APR) and MMMM (e.g. April)
Days: Again you have this correct already. dd will produce 18 for example.
Hours: Your attempt of hh will produce a 12-hour time format. If this is what you are after then fine. But given that you have not attempted to include an AM/PM designator (with can be done with tt by the way) then I would recommend you opt for the 24-hour format which is HH (upper-case)
Minutes: You are correct with your minutes, mm will produce 52 for example.
Seconds: Again, ss is correct and will produce 33 for example.
Now we can string them all together and produce the following format, which includes the 24-hour time format which I would recommend. This can then be passed to the DateTime objects ToString() function like so:
var stringDateTime = slottingmessage.SlottingDateTime.ToString("yyyyMMddHHmmss");
If you wanted to maintain your approach of the GetDateTimeInNewFormat method, then you can implement it like so:
public string GetDateTimeInNewFormat(DateTime dt)
{
return dt.ToString("yyyyMMddHHmmss");
}
This function would then be called the same way you already have in your example code:
GetDateTimeInNewFormat(slottingmessage.SlottingDateTime)
You can read more information about the various date/time formatting options here where there are plenty of examples
Related
I am writing a data parser and trying to work out if a field is a number, a date, a string etc.
The .NET DateTime.TryParse is understandably slow when checking many records (as it checks many different date formats). Therefore, I want to shortcut the processing if possible. A simple check I can do initially is look at the length of the string and reject it if it falls outside of some bounds.
The shortest date I think I should reasonably expect is 6 characters long (e.g. d/M/yy) so I can make the following check:
if (fieldValue.Length < 6)
{
// no datetime is shorter than 6 chars (e.g. d/M/yy is the shotest I can think of)
return false;
}
What is the longest string that still represents a parse-able DateTime?
(For example, "Wednesday, 30th September 2020 12:34:56" is pretty long but I bet there are longer examples!)
A few points:
I am not looking for tricksy answers where the date is padded out with white space or something like that.
I am focused on English dates initially but would be interested if other cultures can throw up longer examples.
What is the longest string that still represents a parse-able
DateTime?
Take a look at the list of custom format specifiers for a DateTime, and take all of those into account.
For instance, this:
DateTime dt = DateTime.Now;
string strNow = dt.ToString("dddd, MMMM dd, yyyy gg hh:mm:ss.fffffff tt K");
Console.WriteLine(strNow);
Gives:
Tuesday, June 16, 2020 A.D. 08:47:02.2667911 AM -06:00
But those different types of values can be output differently based on the information in the DateTime. Look CLOSELY at all the different possible outputs for each specifier in the documentation to see what I mean.
There are many different ways of representing dates, based on the culture you're using.
Let's say I take the US date for January 2nd, 2018: "1/2/2018".
I want to make a method that returns the same value in the same culture format but with only two digits for the year component.
For example:
dd/mm/yyyy -> dd/mm/yy
mm/dd/yyyy -> mm/dd/yy
yyyy-mm-dd -> yy-mm-dd
I want to take a DateTime variable and return the same date variable in the same culture but with the year in the format yy.
Is it ok for every culture if i do something like this?
var year = mydate.ToShortDate.ToString("yy");
var date = mydate.ToShortDate.Substring(0, mydate.Count() - 4) + year;
My input will be .ToShortDate() in many cultures
There is no proper way to do this as far as I know, so the following should be considered a hack.
Let's assume that the date is held in a DateTime. How it got there is not important.
Now the task is to convert it to a string representation according to the short date format, whatever that might be, but with yyyy instead of yy.
http://www.basicdatepicker.com/samples/cultureinfo.aspx
It looks like short date formats contain either yyyy or yy in pretty much all cultures, so let's make that assumption.
The conversion can now be done in this way.
var sampleDate = new DateTime(1992, 12, 31);
var formatString = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
var newFormatString = formatString.Replace("yyyy", "yy");
var sampleDateAsString = sampleDate.ToString(newFormatString);
If the original format string does not contain "yyyy", then the new format string will be the same as the original.
Of course you can get the ShortDatePattern for any culture, not only the current culture as shown here.
I was trying to convert a numeric value to 24 hours format time but the code is not working. Here is my code:
string xx =
Convert.ToDateTime(TimeSpan.FromHours(01).ToString())
.ToString("HH", System.Globalization.CultureInfo.InvariantCulture);
OR
string xx1 =
new DateTime(TimeSpan.FromHours(01).Ticks)
.ToString("HH", System.Globalization.CultureInfo.InvariantCulture);
OR
var t = DateTime.Now.TimeOfDay;
string xx2 =new DateTime(t.Ticks).ToString("hh:mm:ss tt");
OR
string ss = TimeSpan.FromHours(01).ToString("HH");
The above code is not working. I searched Google and everyone said use HH for getting hour in 24 hours format. Can anyone tell me if this is specific issue to my PC?
getting no error rather first line of code return 01 instead of 13.
Because you adding 1 hour from midnight. You should add 13 hour instead like;
string xx = Convert.ToDateTime(TimeSpan.FromHours(13).ToString())
.ToString("HH", System.Globalization.CultureInfo.InvariantCulture);
Since TimeSpan.FromHours(01).ToString() returns 01:00:00 as a string, Convert.ToDateTime parse this string as 13/01/2015 01:00:001.
And 24-hour clock representation of a 01 will be the same as itself no matter you use hh or HH specifier.
On your second example, you calculate your TimeSpan as a Ticks and DateTime(Int64) constructor calculates this time from 01/01/0001 and your DateTime evantually will be 01/01/0001 01:00:00 and still, it's 24-hour clock representation will be 01.
On your third example, you are calling DateTime(Int64) constructor with TimeOfDay property, that's why your DateTime will be 01.01.0001 15:10:36 (when I run your example right now) and it's hh:mm:ss tt representation will be 03:11:31 PM in InvariantCulture.
Your fourth line throws FormatException because there is no standard or custom HH format specifier of a TimeSpan.
1: Since you parse only hour without date, this method returns date part as a today
Setting format for the date
#String.Format("{0:D}", Model.Date)
Code above shows the date in the following format: (13 January 2012)
The required output: (Friday 13 January 2012)
Is there a format for this pattern?
Yep, here you go.
String.Format("{0:dddd d MMMM yyyy}", Model.Date)
Full MSDN Documentation
The general rule I use to remember these formats is like this:
one character means the number alone;
two characters means add a leading zero if necessary
three characters means use three letters if day or month, four numbers for year
four letters means use full word for day or month
Extra stuff (not special characters) just gets put in the string
e.g. Consider 1st Jan 2001
String.Format("{0:(d;dd;ddd;dddd),(M;MM;MMM;MMMM),(y,yy,yyy,yyyy)}", DateTime.Parse("2001/01/01"))
will return
(1;01;Mon;Monday),(1;01;Jan;January),(1,01,2001,2001)
Similar rules for times, like this:
String.Format("{0:(h;hh):(m;mm):(s,ss) (t,tt)}", DateTime.Now)
to give this:
(9;09):(41;41):(34,34) (P,PM)
DateTime now = DateTime.Now;
Console.WriteLine(String.Format("{0:dddd d MMMM yyyy}",now));
//output = Friday 13 January 2012
if you want the standard date format just use
Console.WriteLine(now.ToString("D"));
here is something I wrote real quick as well to help you in the future if you want to see what you can to with the now.ToString() in regards to passing formats.
try this out in a Console Application to see the results.. Cheers
DateTime now = DateTime.Now;
Console.WriteLine(now.ToString("d"));
Console.WriteLine(now.ToString("D"));
Console.WriteLine(now.ToString("f"));
Console.WriteLine(now.ToString("F"));
Console.WriteLine(now.ToString("g"));
Console.WriteLine(now.ToString("G"));
Console.WriteLine(now.ToString("m"));
Console.WriteLine(now.ToString("M"));
Console.WriteLine(now.ToString("o"));
Console.WriteLine(now.ToString("O"));
Console.WriteLine(now.ToString("s"));
Console.WriteLine(now.ToString("t"));
Console.WriteLine(now.ToString("T"));
Console.WriteLine(now.ToString("u"));
Console.WriteLine(now.ToString("U"));
Console.WriteLine(now.ToString("y"));
Console.WriteLine(now.ToString("Y"));
Console.Read();
As #Dommer points out String.Format("{0:dddd d MMMM yyyy}", Model.Date) gives you the result you want. And here you'll find MSDN documentation on date and time formats.
If you need to be culturally-aware then use Format(IFormatProvider, String, Object()).
String.Format(CultureInfo.InvariantCulture, "{0:D}", Model.Date);
An api im using is providing me a date. This date is of type string and is presented in the format:
Mon Nov 16 19:15:09 +0000 2009
DateTime.TryParse() fails when this value is provided. Can anyone point me in the right direction?
Using the DateTimeOffset class in order to handle the offset.
[TestMethod]
public void test()
{
string s = "Mon Nov 16 19:15:09 +0000 2009";
var result = DateTimeOffset.ParseExact(
s,
"ddd MMM dd HH:mm:ss zzz yyyy",
System.Globalization.CultureInfo.InvariantCulture);
Assert.AreEqual(16, result.Day);
Assert.AreEqual(11, result.Month);
Assert.AreEqual(2009, result.Year);
Assert.AreEqual(19, result.Hour);
Assert.AreEqual(15, result.Minute);
Assert.AreEqual(9, result.Second);
Assert.AreEqual(0, result.Offset.Hours);
}
Change the offset in the string - e.g. '0600' and then change the offset assertion to match, it'll work.
You can then convert this into a DateTime if you have to - but you lose the offset information; so you have to decide whether you're going to keep it as the original local time (19:15:09), or if you're going to convert to some standard time (e.g. 13:19:05 UTC if offset is +06:00).
It gets interesting if you need to convert that to your own local time - because it would depend on what DST rules were in place in 2009 at that time of the year - that can cause a real headache!
So, if you're going to DateTime I recommend converting to universal time and then go from there. Add this to the test:
Console.WriteLine(result);
//little bit long winded - but you need the 'Universal' Kind for reliability
Console.WriteLine(
DateTime.SpecifyKind(
new DateTime(result.ToUniversalTime().Ticks),
DateTimeKind.Utc)
);
This outputs:
11/16/2009 19:15:09 +06:00
11/16/2009 13:15:09
Try DateTime.TryParseExact passing a suitable format string.
Because the DateTime.TryParse(String, DateTime) method tries to parse the string representation of a date and time using the formatting rules of the current culture, trying to parse a particular string across different cultures can either fail or return different results. If a specific date and time format will be parsed across different locales, use the DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime) method or one of the overloads of the TryParseExact method and provide a format specifier.
One of the TryParse methods accepts an IFormatProvider, which can also come as a DateTimeFormatInfo class. The following link has all the necessary details:
http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx
Yours would be almost like: ddd, MMM dd yyyy HH':'mm':'ss zzz yyyy
The only problem is the timezone offset, zzz includes a colon between the hours and minutes. You might get away with using zz'00' though it is cheating.