Getting error while parsing string to datetime.
string datestring = "111815";
DateTime date = Convert.ToDateTime(datestring);
I also tried using, Parse, ExactParse with/without culture specificinfo.
I'm still getting the error:
String was not recognized as a valid DateTime.
Please suggest the correct solution.
You just need to specify the right format string when you call ParseExact. In your case, it looks like this is month-day-year, without any separators, and with a 2-digit year (blech). So you'd parse it like this:
using System;
using System.Globalization;
class Test
{
static void Main()
{
DateTime dt = DateTime.ParseExact("111815", "MMddyy", CultureInfo.InvariantCulture);
Console.WriteLine(dt);
}
}
If you're in control of the format at all, I'd strongly recommend yyyy-MM-dd instead of this ambiguous (due to the 2-digit years) and US-centric (due to month/day/year) format.
Related
I wonder is it possible to parse clock time hour:minute:second in Java 8?
e.g.
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
final String str = "12:22:10";
final LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
I tried but get this exception:
Exception in thread "main" java.time.format.DateTimeParseException: Text '12:22:10' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 12:22:10 of type java.time.format.Parsed
LocalTime.parse
Since you only have a time use the LocalTime class. No need to define a formatting pattern in your case.
String str = "12:22:10";
LocalTime time = LocalTime.parse(str);
See that code run live at IdeOne.com.
See Oracle Tutorial for more info.
LocalTime.parse("04:17");
I developed WCF service that contains so many methods and these methods return json format. My main problem is when i have datacontract member has datetime type i get in json like this /Date(1233846970110-0500)/ which is causing me issue in IOS application. How can i write a global method that converts to MM/dd/yyyy format for very call. I tried to different methods but none works when i test it, always returns the same above format.
I tried in global.ascx like this but like
private void RegisterRoutes()
{
// Create Json.Net formatter serializing DateTime using the ISO 8601 format
var serializerSettings = new JsonSerializerSettings();
serializerSettings.Converters.Add(new IsoDateTimeConverter());
var config = HttpHostConfiguration.Create().Configuration;
config.OperationHandlerFactory.Formatters.Clear();
config.OperationHandlerFactory.Formatters.Insert(0, new JsonNetMediaTypeFormatter(serializerSettings));
var httpServiceFactory = new HttpServiceHostFactory
{
OperationHandlerFactory = config.OperationHandlerFactory,
MessageHandlerFactory = config.MessageHandlerFactory
};
RouteTable.Routes.Add(new ServiceRoute("VWPM_Srv", httpServiceFactory, typeof(IVWPM_Srv)));
}
If you want to send an MM/dd/yyyy formatted string. You just make the property a string and assign the date in the MM/dd/yyyy format.
However you can also make ios accept the dates wfc send you:
json-serialized-date-passed-between-ios-and-wcf-and-vice-versa
I am struggling with linq to get the datetime.
I am trying to get the info if the records are less than the current date
Here is the code:
public ActionResult _Events()
{
DateTime dt = DateTime.Now.Date;
var DocsFirst =(from t in db.tble_presentation
where dt >= EntityFunctions.TruncateTime(t.presentation_date)
select t).OrderByDescending(t => t.presentation_date).Take(2);
return PartialView(new Newsmodel
{
DocsList_list1 = DocsFirst,
});
}
but I get this following error
Cannot implicitly convert type 'System.Linq.IQueryable' to
'System.Linq.IOrderedEnumerable'. An explicit conversion exists
(are you missing a cast?)
thanks in advance
Hesh
It looks like DocsList_List1 is of type IOrderedEnumerable (as #Emre points out in the comment). To make the code compile, you either have to change the declaration of DocsList_list1 to be of a compatible type (probably IEnumerable) or make the result of the linq query an IOrderedEnumerable. An (somewhat ugly) way to do the latter:
var DocsFirst = (from t in db.tble_presentation
where dt >= EntityFunctions.TruncateTime(t.presentation_date)
select t).Take(2).AsEnumerable()
.OrderByDescending(t => t.presentation_date);
It's somewhat ugly because it does the ordering in memory instead of letting the database do it, but it still only reads the two requested elements thanks to Take(2) being placed before AsEnumerable().
In my grails domain I am having a field Date i.e. java.util.Date.
In my controller I am loading this date from params using SimpleDateFormate.
To be precise assume that params.date is something like '20/02/2013 02:30 am'. In the controller I load this as follows:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm a");
domainInstance.date = simpleDateFormat.parse(params.date)
While this statement executes no error is detected. However when the domain Instance is being saved error is generated that
[typeMismatch.Domain.date,typeMismatch.date,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes
[Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'date'; nested exception is java.lang.IllegalArgumentException: Could not parse date: Unparseable date: "20/02/2013 02:30 am"]
Can you anyone tell me where things are going wrong.
I am pretty sure that SimpleDateFormat parses String to Date. Why is it accepting as String.
Thanks for the response, but I have found the solution to the problem. The problem was something like this.
I was instantiating my domainInstance as domainInstance = new Domain(params)
This was the first statement in the controller action.
When this statement is executed params holds the date in the format "dd/MM/yyyy HH:mm a". Hence this statement adds an error in the domainInstance object.
Later after using SimpleDateFormat the variable is updated but the error still remains in the object because of which the error crops up.
The solution to this error is immediately after the statement 'domainInstance = new Domain(params)' call the statement domainInstance.clearErrors().
This clears up all the errors in the object. Later when the domainInstance is being saved validate is called. In case validate fails due to some other error then the respective error is added at that time.
Rammohan
Grails 2.3.1 is actual problem
def domain = new FooBar(params)
domain.clearErrors()
domain.save(flush:true) // <--- validation will be there
if (doamin.hasErrors()) {
... do something
}
You can try:
domainInstance.date = new Date().parse("dd/MM/yyyy HH:mm a", params.date)
I'm working on a biztalk project and use a map to create the new message.
Now i want to map a datefield to a string.
I thought i can do it on this way with an Function Script with inline C#
public string convertDateTime(DateTime param)
{
return System.Xml.XmlConvert.ToString(param,ÿyyyMMdd");
}
But this doesn't work and i receive an error. How can i do the convert in the map?
It's a Biztalk 2006 project.
Without the details of the error you are seeing it is hard to be sure but I'm quite sure that your map is failing because all the parameters within the BizTalk XSLT engine are passed as strings1.
When I try to run something like the function you provided as inline C# I get the following error:
Object of type 'System.String' cannot be converted to type 'System.DateTime'
Replace your inline C# with something like the following:
public string ConvertDateTime(string param1)
{
DateTime inputDate = DateTime.Parse(param1);
return inputDate.ToString("yyyyMMdd");
}
Note that the parameter type is now string, and you can then convert that to a DateTime and perform your string format.
As other answers have suggested, it may be better to put this helper method into an external class - that way you can get your code under test to deal with edge cases, and you also get some reuse.
1 The fact that all parameters in the BizTalk XSLT are strings can be the source of a lot of gotchas - one other common one is with math calculations. If you return numeric values from your scripting functoids BizTalk will helpfully convert them to strings to map them to the outbound schema but will not so helpfully perform some very random rounding on the resulting values. Converting the return values to strings yourself within the C# will remove this risk and give you the expected results.
If you're using the mapper, you just need a Scripting Functiod (yes, using inline C#) and you should be able to do:
public string convertDateTime(DateTime param)
{
return(param.ToString("YYYYMMdd");
}
As far as I know, you don't need to call the System.Xml namespace in anyway.
I'd suggest
public static string DateToString(DateTime dateValue)
{
return String.Format("{0:yyyyMMdd}", dateValue);
}
You could also create a external Lib which would provide more flexibility and reusability:
public static string DateToString(DateTime dateValue, string formatPicture)
{
string format = formatPicture;
if (IsNullOrEmptyString(formatPicture)
{
format = "{0:yyyyMMdd}";
}
return String.Format(format, dateValue);
}
public static string DateToString(DateTime dateValue)
{
return DateToString(dateValue, null);
}
I tend to move every function I use twice inside an inline script into an external lib. Iit will give you well tested code for all edge cases your data may provide because it's eays to create tests for these external lib functions whereas it's hard to do good testing on inline scripts in maps.
This blog will solve your problem.
http://biztalkorchestration.blogspot.in/2014/07/convert-datetime-format-to-string-in.html?view=sidebar
Regards,
AboorvaRaja
Bangalore
+918123339872
Given that maps in BizTalk are implemented as XSL stylesheets, when passing data into a msxsl scripting function, note that the data will be one of types in the Equivalent .NET Framework Class (Types) from this table here. You'll note that System.DateTime isn't on the list.
For parsing of xs:dateTimes, I've generally obtained the /text() node and then parse the parameter from System.String:
<CreateDate>
<xsl:value-of select="userCSharp:GetDateyyyyMMdd(string(s0:StatusIdChangeDate/text()))" />
</CreateDate>
And then the C# script
<msxsl:script language="C#" implements-prefix="userCSharp">
<![CDATA[
public System.String GetDateyyyyMMdd(System.String p_DateTime)
{
return System.DateTime.Parse(p_DateTime).ToString("yyyyMMdd");
}
]]>