Mulesoft: dataweave convert datestring to a datetime - datetime

I need to convert a date string "23012021235129" to a date like "2021-01-24T00:51:29.006+01:00".
My code:
|23012021235129| as LocalDateTime {format: "ddMMyyyyHHmmss"}) as String {format: "yyyy-MM-dd'T'HH:mm:ss.SSS+01:00"},
Result:
"2021-01-23T23:51:29.000+01:00".
It's almost working except for the millisecond. Please advise what to do?

The input string ("23012021235129") has no milliseconds so it should be expected that in the output the number of milliseconds is zero.

Related

Issue in converting Timespan variable to 12 hour format

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") );

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.

How do I get the timezone from a string containing a datetime value in PHP?

Given the following string: 2011/09/18 11:59PM EDT, 2011-09-18T23:59:59+00:00
How do I extract the timezone part from this string using PHP?
Create a new DateTime object from the string, and use getTimezone on it to get the timezone:
$time = '2011/09/18 11:59PM EDT';
$dt = new DateTime($time);
print_r($dt->getTimezone()->getName());
See it in action.

Resources