Issue in converting Timespan variable to 12 hour format - asp.net

I have a nullable variable Start time
Timespan? st=e.StartTime;//Null-able variable;
I am trying to get time in AM/PM format but I am unable to get it.
DateTime date = Convert.ToDateTime(st.ToString());
String f = String.Format("{0:hh:mm:tt}", date);
Error is:
System.FormatException: String was not recognized as a valid DateTime.

If you were to output the results of st.ToString(), you will find that it doesn't contain any date information, only hours, minutes and seconds.
This isn't a valid format for a DateTime, which generally contain date and time information.
You don't need to convert your TimeSpan to a DateTime to format it, you can just use TimeSpan.ToString():
string f = st.Value.ToString(#"hh\:mm\:tt");
For reference: http://msdn.microsoft.com/en-us/library/ee372287.aspx
Also, note the \ before the :, you must do this if you want to include literal strings in the output, as mentioned at the bottom of that documentation page.

Converting a timespan to a date is not possible, a timespan represents x amount of minutes/hours/whatever and you cannot get an exact date from that alone. If you have a date as a starting point, you can add a timespan and that will give you the new date.

st.ToString() will return "System.Nullable<Timespan>" because that is what a nullable type returns - it does not override the default Object.ToString implementation, so returns the type name.
If you want the string of the actual timespan, then you would need to do st.Value.ToString(), but you should be checking for null first (i.e. st.HasValue == true)
Edit: Also see #Sean's comment about how to output the Timespan without converting to a DateTime first.
Edit: Turns out I was slightly wrong - st.ToString() doesn't return the above. So see Sean's answer.

First convert Timespan to Datetime by adding TimeSpan to a base date of 00:00 hrs. Then on that dateTime derive the 12 hr format.
DateTime.Now.Date.Add(OpenTimeSpan).ToString(#"hh\:mm\:tt")

The Accepted Answer is wrong.
You cannot return AM/PM for a TimeSpan because it is only concerned with the length of Time,
not a Time of Day - hench the name, "TimeSpan".
Convert to a DateTime first before converting to a String:
string sTimeOfDay = new DateTime().Add(st).ToString("hh:mm tt");
Note: If your TimeSpan is nullable, then you will need to add Conditional Logic to Handle Nulls and pass in ts.Value instead of ts:
string sTimeOfDay = (st == null ? null : new DateTime().Add(st.value).ToString("hh:mm tt") );

Related

json.net deserialize datetime in object

I have a problem with deserialization of datetime. In JSON it comes in this format 2016-10-04T15:20:00 but after deserialialization it changes to the AM/PM time format and I need to preserve the 24 hour format. Is there any way how specify the format?
When you deserialize to a date, the format is not stored inside the date object. Instead, the formatting happens on output. The default format for your locale is probably using 12-hour time. If you want a different format, you can pass a format string to the ToString method:
string json = #"{ ""date"": ""2016-10-04T15:20:00"" }";
Foo foo = JsonConvert.DeserializeObject<Foo>(json);
Console.WriteLine(foo.Date.ToString("yyyy-MM-dd HH:mm:ss"));
Fiddle: https://dotnetfiddle.net/ibLCbG

Parse alfresco date

I'm developing a custom validator of a date input in my workflow form and I get a null after parsing a date this is what I done:
// check dates can be parsed
str_expiryDate = field.form.prop_wfbxTestWorkFlow_NfDate.value;
console.log("Non conformite"+str_expiryDate);
str_reminderDate = field.form.prop_bpm_workflowDueDate.value;
console.log("echeance"+str_reminderDate);
Alfresco.logger.warn("Expiry Date: " + str_expiryDate + " | Reminder Date: " + str_reminderDate);
d_expiryDate = Date.parse(str_expiryDate);
console.log("nfDate"+str_expiryDate);
d_reminderDate = Date.parse(str_reminderDate);
console.log("Date echéance"+d_reminderDate);
and then i get this in console:
Non conformite2013-06-21T00:00:00.000+01:00 echeance2013-06-09T00:00:00.000+01:00
nfDatenull
Date echéancenull
How I can parse these two dates and then compare it? .thanks
Use Alfresco.util.fromISO8601(date)
According to the client-api docs
Convert an ISO8601 date string into a JavaScript native Date object
You are parsing the "value" of a date, not the date itself.
The best way to compare is, imho, using the format YYYYMMDD, and than compare it as a number.
Something like this (there is sure a far more elegant way to do that, but at this time it's the only one that got me):
var indexDate=str_expiryDate.indexOf("-");
var dayDate=str_expiryDate.substring(0, 2);
var monthDate=str_expiryDate.substring(3, 5);
var yearDate=fromData.substring(6, str_expiryDate.length+1);
int dataNew=yearDate+monthDate+dayDate;
and than compare the two dates value.
Obviously check if the index value are correct, I didn't double checked them.
Hope il helps.

How do I validate a string to be a date in the format dd-M-y, and not be a past date?

I have a date field and the format is "dd-M-y", example 01-Jan-2013. First I want to check the format which must be "dd-M-y" and secondly the date shouldn't be in the past but can be today and onward.
How would I do that? I would like to use regular expressions but I don't know what a suitable one would be.
You should use DateTime.TryParseExact rather than using Regex to validate your DateTime
string testDate = "01-Jan-2013";
DateTime temp;
if (DateTime.TryParseExact(testDate,
"dd-MMM-yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out temp) &&
(temp > DateTime.Today))
{
//Valid date and greater than today
}
else
{
//Invalid date or less than today
}
I think you should bind the user to fill the date in correct format instead of checking for it...
The Best solution in this case would be MaskEditExtender

asp.net c# - combine / format a date and time from separate sources

I'm parsing an XML file from an external source, and I have 2 attributes which contain the date and time respectively. I'm looking for the best way to get these into a format I can parse as a date so I can do things with it, but at the moment I'm just getting errors or no results with the methods I've tried.
The date is in the format "20111215" - which is yyyymmdd as it's UK based.
The time is formatted as "1417+0000" which I presume is the time plus offset from GMT?
Basically I need to get these into UK time. I've tried using DateTime.Parse on the separate parts but both give an error as not valid format. Tried String.Format on the date part but that didn't change it at all. I presume I need to combine the 2 before parsing but I'm not sure if I need to do anything else with it to make it acceptable.
Any help appreciated.
Use a DateTimeOffset to incorporate the timezone into the DateTime.
string date = "20111215";
string time = "1417+0500";
string dateAndTime = date + time;
string format = "yyyyMMddHHmmzzz";
CultureInfo provider = CultureInfo.InvariantCulture;
DateTimeOffset t = DateTimeOffset.ParseExact(dateAndTime, format, provider);
If you concatenate the fields together, you can then use DateTime.TryParseExact in order to parse them into a DateTime.
string input = string.Format("{0} {1}", dateString, timeString);
DateTime parsed;
if(DateTime.TryParseExact(input,
"yyyyMMdd HHmmK",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out parsed))
{
// parsed OK, use the parsed variable
}
string date = "20111215";
string time = "1417+0000";
string dateString = date + time;;
string format = "yyyyMMddHHmmK";
// or something similar, I'm not sure about the timezone
DateTime result = DateTime.ParseExact(dateString,
format,
CultureInfo.InvariantCulture);
I think this should work (i didn't test it):
string dateString = "20111215";
string timeString = "1417+0000";
int year = int.Parse(dateString.Substring(0,4));
int month = int.Parse(dateString.Substring(4,2));
int day = int.Parse(dateString.Substring(6,2));
int hour = int.Parse(dateString.Substring(0,2));
int mins = int.Parse(dateString.Substring(2,2));
DateTime d = new DateTime(year, month, day, hour, mins, 0);

How To Parse Date From any datetime format to dd/mm/yyyy?

i want to parse any datetime format to dd/MM/yyyy format.
here is my code
// dates i am providing are
// Sat, 01 Oct 2011 17:30:00 +0400
// and
// Sat, 01 October 2011 12:21:23 EST
Datetime dt = Convert.toDateTime(pubDate);
which is giving me following exception
The string was not recognized as a valid DateTime. There is an unknown word starting at index 32
any one guide me how can i parse any dateformat to a single one?
any help would be appreciated.
DateTime doesn't store dates in a "format" - it uses an internal representation. You need to parse a passed in string in order to get the correct value for the DateTime and when you want to display it you can then format it to whatever display.
Your best bet is to use TryParseExact supplying it with the exact format string. You need to use the custom Date and Time format strings with it.
Use the overload that takes a string[] of format strings - one for each date format.
In regards to the EST portion - the framework doesn't have support for named timezones. You may want to write a wrapper that converts named timezones to their equivalent but parseable form.
Untested (based on MSDN example):
string[] formats= {"ddd, dd/MMM/yyyy hh:mm:ss K",
"ddd, dd MMMM yyyy hh:mm:ss EST"};
DateTime dateValue;
foreach (string dateString in dateStrings)
{
if (DateTime.TryParseExact(dateString, formats,
new CultureInfo("en-US"),
DateTimeStyles.None,
out dateValue))
Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
else
Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
}
Remove the 'EST' from the string and it should work.

Resources