DateTime Format like HH:mm 24 Hours without AM/PM - c#

I was searching here about converting a string like "16:20" to a DateTime type without losing the format, I said I dont want to add dd/MM/yyy or seconds or AM/PM, because db just accept this format.
I tried with Cultures yet
Thanks in Advance

Just give a date format to your dateTime.
string DateFormat = "yyyy MM d " this willl give you the year month and day. after continuing;
string DateFormat = "yyyy MM d HH:mm:ss " in here the Capital H will give you the 24 hours time format and lowerCase "h" will give you the 12 hours time format...
when you give the Dateformat as a string you can do whatever you want with date and time.
string DateFormat = "yyyyMMdHHmmss";
string date = DateTime.Now.ToStrign(DateFormat);
OR
Console.writeline(DateTime.Now.ToStrign(DateFormat));
OUTPUT:
20120823132544

All DateTime objects must have a date and a time.
If you want just the time, use TimeSpan:
TimeSpan span = TimeSpan.Parse("16:20");
If you want a DateTime, add that time to the min value:
TimeSpan span = TimeSpan.Parse("16.20");
DateTime dt = DateTime.MinValue.Add(span);
// will get you 1/1/1900 4:20 PM which can be formatted with .ToString("HH:mm") for 24 hour formatting

DateTime.Now.ToString("hh:mm") - If it's C#.
Oh. Only read the header.
DateTime dt = new DateTime(2008, 12, 11, Convert.ToInt32("16"), Convert.ToInt32("32"), 0);

what do you mean by "losing the format".
if you convert it to a DateTime type, then the DateTime object will have dd/mm/yy and other properties. depending on how you plan to use the object, you can "recover" your original settings, by formatting the string output like this: DT.ToString("HH:mm");

Since you don't stipulate which DBMS you are using, it is hard to know which answer will help you. If you use IBM Informix Dynamic Server, you would simply use the data type 'DATETIME HOUR TO MINUTE', which will record values in the 24 hour clock.

DateTime.Parse("16:20")

I want to address this part of your question:
without losing the format
A database will generally store all datetime values in a standard common format that's not even human readable. If you use a datetime column the original format is destroyed.
However, when you retrieve the value you cast it back to any format you want. If you want HH:mm you can get it.

Related

Parsing Date Time in C#, Getting wrong output

I am trying to parse the date by using below code
DateTime mydate = DateTime.ParseExact(datetoconvert,"dd/mm/yyyy",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
but its output is wrong, the datetoconvert in above code is 30/Mar/2017 but output is 29/Jan/2017
looking forward for your valuable answers...
Lowercase mm means minute, use MM
DateTime mydate = DateTime.ParseExact(datetoconvert,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
If you want to output it as 30/Mar/2017(different topic):
string result = mydate.ToString("dd/MMM/yyyy", CultureInfo.InvariantCulture);
But note that / has a special meaning too(in Parse and ToString). It will be replaced with your current cultures date-separator which seems to be / but fails with a different. You can avoid it by specifying CultureInfo.InvariantCulture or by masking it by wrapping it with apostrophes:
DateTime mydate = DateTime.ParseExact(datetoconvert,"dd'/'MM'/'yyyy",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
replace
"dd/mm/yyyy"
with
"dd/MMM/yyyy"
because "Jan" is matched by MMM instead of mm (for minutes)
Reference
"MMM" The abbreviated name of the month.
https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
The date format is wrong. try "dd/MM/yyyy" instead of "dd/mm/yyyy"
If you need abbrivated month name, use "dd/MMM/yyyy"

DateTime ParseExact not working when changing time

I'm having trouble figuring out why my date is parsed correctly until I change the time of the date passed into the parse method.
var parsedDate = DateTime.ParseExact("2016-02-05T07:00:00+00:00", "yyyy-MM-ddThh:mm:ss+00:00", CultureInfo.InvariantCulture);
dateValueToTryParse = parsedDate.ToString("dd/MM/yyyy");
The required result is outputted and I do get 05/02/2016. However, if I change the string passed in to:
2016-02-19T23:59:00+00:00
The output of dateValueToTryParse remains the same and it is not parsed correctly. Am I doing anything particularly wrong with my parsing? I'm confused as the format seems to be exactly the same?
You need to change your incoming format to yyyy-MM-ddTHH:mm:ss+00:00.
The difference is HH. Capital H means 24 hour clock or "military time".
Otherwise, it is trying to parse hour 23 which doesn't exist.
See here for more detailed information on other formats: https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
Changing hh to HH specifier can solve your problem but since your string has an UTC offset value, I would prefer to parse it to DateTimeOffset instead of DateTime for consistency.
var dto = DateTimeOffset.ParseExact("2016-02-05T23:00:00+00:00",
"yyyy-MM-ddTHH:mm:sszzz",
CultureInfo.InvariantCulture);
Now, you have a DateTimeOffset as {05.02.2016 23:00:00 +00:00} and you can use it's .DateTime property to get the DateTime value represented by it.
var dateValueToTryParse = dto.DateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
This will generate 05/02/2016 as a result.

Not reading CSV correctly when any date field is there

csv file data -
DB PID Date1 Date2
--------------------------------
DB1 561 06-04-2015 06-05-2015
DB2 538 06-04-2015 08-21-2015
DB3 722 06-04-2015 08-21-2015
Here date format is stated as MM-DD-YYYY. Problem is while reading Date2 columns date then it's reading date as DD-MM-YYYY. That's why in 08-21-2015 '08' becomes DD and '21' becomes month and got validation error.
Tried to solve the code :
Date2Val = Convert.ToDateTime(TestContext.DataRow["Date2"]).ToString("dd-MM-yyyy 00:00:00.000");
It works for Date1 column but not for Date2.
Convert.ToDateTime uses standard date and time format of your CurrentCulture.
That means your CurrentCulture has dd-MM-yyyy as a standard date and time format, not MM-dd-yyyy.
You can explicitly specify your format with custom date and time specifiers in DateTime.ParseExact method like;
Date2Val = DateTime.ParseExact(TestContext.DataRow["Date2"].ToString(),
"MM-dd-yyyy",
CultureInfo.InvariantCulture)
.ToString("dd-MM-yyyy 00:00:00.000");
You need to explicitly state the format for the date value, as DateTime.Parse always uses the date format that's configured in your system's culture information.
The following uses the format you need:
Date2Val = DateTime.ParseExact(TestContext.DataRow["Date2"].ToString(), "MM-dd-yyyy", CultureInfo.InvariantCulture).ToString("dd-MM-yyyy 00:00:00.000");
After much ado you just told us there's not only a date value in Date2, but also a time part. In that case you need to use this:
Date2Val = DateTime.ParseExact(TestContext.DataRow["Date2"].ToString(), "MM-dd-yyyy HH:mm:ss", CultureInfo.InvariantCulture).ToString("dd-MM-yyyy 00:00:00.000");
Perhaps force the data to strings, to prevent the auto-conversion and then in the code parse it to a DateTime.
I put double qoutes around the data top force it as text. That gives back strings, without removing the quotes.
columnInt, columnString
1, "11.12.89"
2, "12.12.89"

Is there a way to format a date time object?

So last week, the way our application worked was that the back-end team was storing dates as a string in YYYY-MM-DD formats. This week, they changed it to be a DateTime object instead of a string. So now I'm just creating a DateTime object from the string value on this particular DateTime control we use.
So basically with our custom control , it was like this:
mySearchModelObject.fromDate = myDateRangeControl.Values[0]; //string
mySearchModelObject.toDate = myDateRangeControl.Values[1]; //string
Now it's more like this:
DateTime fromDate, toDate;
DateTime.Tryparse(myDateRangeControl.Values[0], out fromDate);
DateTime.Tryparse(myDateRangeControl.Values[1], out toDate);
mySearchModelObject.fromDate = fromDate;
mySearchModelObject.toDate = toDate;
But searching with the same date range as last week yields different results from the DB.
I'm wondering if it's because our dates were "YYYY-MM-DD" as strings, but now it's getting a date time object in whatever the system's format is + the time itself.
So is there a way to format my DateTime object to still have it in the same YYYY-MM-DD format?
Use DateTime.TryParseExact and provide "yyyy-MM-dd" as format string.
See http://msdn.microsoft.com/en-us/library/h9b85w22
you can do fromDate.ToString("yyyy-MM-dd") to have a date formatted as YYYY-MM-DD
see msdn on standard and custom datetime format
see demo https://dotnetfiddle.net/NZz0HG
also if mySearchModelObject.fromDate is of type object, you can assign a DateTime or a string, no compiler warnings/error.
But when is used, maybe with mySearchModelObject.fromDate.ToString() you get a different result, before was '2014-12-31' and now 12/31/2014 12:00:00 AM

How to parse a string into a date time format in C#

i have a string which contains date time this...
string S="08/18/2013 24:00:00"
DateTime DT = DateTime.ParseExact(S, "MM/dd/yyyy HH:mm:ss", null);
i want to parse it into date time but shows an exception like this.
The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.
please tell me any solution for this problem.
The problem is with the hour being 24. DateTime doesn't support this, as far as I'm aware.
Options:
Use my Noda Time project which does support 24:00:00, but basically handles it by adding a day (it doesn't preserve a difference between that and "end of previous day")
Keep using DateTime, manually replace "24:00:00" with "00:00:00" when it occurs, and remember to add a day afterwards
If you want to preserve the information that it was actually "end of the day" you'd need to do that separately, and keep the information alongside the DateTime / LocalDateTime.
You should also parse with the invariant culture as other answers have suggested - you're not trying to parse a culture-specific string; you know the exact separators etc.
string S="08/18/2013 00:00:00"; // here is the first problem occurred
DateTime DT = DateTime.ParseExact(S, "MM/dd/yyyy hh:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
From The "HH" Custom Format Specifier
The "HH" custom format specifier (plus any number of additional "H"
specifiers) represents the hour as a number from 00 through 23; that
is, the hour is represented by a zero-based 24-hour clock that counts
the hours since midnight.
So, using 24 as an hour is invalid on this case.
Try with hh format with 00 instead like;
string S = "08/18/2013 00:00:00";
DateTime DT = DateTime.ParseExact(S, "MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture);
Here a DEMO.
If you really want to use 24:00:00 as a hour, take a look Noda Time which developed by Jon.

Categories

Resources