Scala date formatting from Mysql - mysql

Having trouble with date formatting, I have the code below:
BUT i get [IllegalArgumentException: Cannot format given Object as a Date] in Play 2.1-RC3
def formatDate(indate: Date) : String = {
val dateFormat = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
val datedate = dateFormat.format(indate)
datedate
}
val fdate = Extrastuff.formatDate("2012-10-08 15:16:56.0")

If I understood you right then method formatDate accepts object of type Date (indate: Date), but you are trying to use it with a string.

Related

Newtonsoft deserializing Json incorrectly

I have encountered a case where Newtonsoft is taking perfectly valid JSON text, but deserializing it incorrectly. I have an object that contains an embedded class that consists of members Year, Month, Week, and DayOfWk. The JSON looks like this:
"openDate": {
"Year": 1997,
"Month": 12,
"Week": 5,
"DayOfWk": 5
},
But the data that comes back after deserialization is Year = 1, Month = 1, Week = 1, and DayOfWk = 1, regardless of the input JSON.
Here is the code (it's in F#, but should be easily readable):
let jsonText = File.ReadAllText( #"..\..\..\..\Dependencies\ADBE.dat")
let dailyData = JsonConvert.DeserializeObject<DailyAnalysis[]>(jsonText)
DailyAnalysis is defined as:
type DailyAnalysis = {
openDate: TradeDate
openPrice: Decimal
closeDate: TradeDate
closePrice: Decimal
gainPercentage: Decimal
}
TradeDate is the class in question - it is an F# class that exposes properties Year, Month, Week, and DayOfWk. Year, Month, and Week are int's; DayOfWeek is a DayOfWeek enum. All the other fields in the DailyAnalysis objects come back with the correct values.
How can this problem be resolved?
Note that if I don't include the type in the DeserializeObject call, it does get the correct data, but simply returns it as an object, and converting to the correct type is very difficult (i.e., I don't know how to do it in F#).
Can anybody point out something obvious (or even obscure) I'm overlooking, or point me to other resources?
Update: note that the constructor for TradeDate takes a single DateTime argument.
Assuming that your TradeDate is immutable (as typically happens in f#), then Json.NET is able to deserialize such a type by finding a single constructor which is parameterized, then invoking it by matching constructor arguments to JSON properties by name, modulo case. Arguments that do not match are given a default value. If TradeDate actually takes a single DateTime as input, you will get the behavior you are seeing.
For instance, if we take a simplified version like so:
type TradeDate(date : DateTime) =
member this.Year = date.Year
member this.Month = date.Month
member this.DayOfMonth = date.Day
And then round-trip it using Json.NET as follows:
let t1 = new TradeDate(new DateTime(1997, 12, 25))
let json1 = JsonConvert.SerializeObject(t1)
let t2 = JsonConvert.DeserializeObject<TradeDate>(json1)
let json2 = JsonConvert.SerializeObject(t2)
printfn "\nResult after round-trip:\n%s" json2
The result becomes:
{"Year":1,"Month":1,"DayOfMonth":1}
Which is exactly what you are seeing. Demo fiddle #1 here.
So, what are your options? Firstly, you could modify TradeDate to have the necessary constructor, and mark it with JsonConstructor. It could be private as long as the attribute is applied:
type TradeDate [<JsonConstructor>] private(year : int, month : int, dayOfMonth: int) =
member this.Year = year
member this.Month = month
member this.DayOfMonth = dayOfMonth
new(date : DateTime) = new TradeDate(date.Year, date.Month, date.Day)
Demo fiddle #2 here.
Secondly, if you cannot modify TradeDate or add Json.NET attributes to it, you could introduce a custom JsonConverter for it:
[<AllowNullLiteral>] type private TradeDateDTO(year : int, month : int, dayOfMonth : int) =
member this.Year = year
member this.Month = month
member this.DayOfMonth = dayOfMonth
type TradeDateConverter () =
inherit JsonConverter()
override this.CanConvert(t) = (t = typedefof<TradeDate>)
override this.ReadJson(reader, t, existingValue, serializer) =
let dto = serializer.Deserialize<TradeDateDTO>(reader)
match dto with
| null -> raise (new JsonSerializationException("null TradeDate"))
| _ -> new TradeDate(new DateTime(dto.Year, dto.Month, dto.DayOfMonth)) :> Object
override this.CanWrite = false
override this.WriteJson(writer, value, serializer) =
raise (new NotImplementedException());
And deserialize as follows:
let converter = new TradeDateConverter()
let t2 = JsonConvert.DeserializeObject<TradeDate>(json1, converter)
Demo fiddle #3 here.
Notes:
Your question did not include code for TradeDate, in particular the code for converting between a DateTime and the year/month/week of month/day of week representation. This turns out to be slightly nontrivial so I did not include it in the answer; see Calculate week of month in .NET and Calculate date from week number for how this might be done.
For details on how Json.NET chooses which constructor to invoke for a type with multiple constructors, see How does JSON deserialization in C# work.

Inserting date in Mysql (codename one)

I want to insert a Date object in mysql database, which has a Date type in the database as well. I am having problems inserting the date .
I have tried this code, but it seems codename one have a problem with it:
dateString s;
s = date.getCurrentMonth() + "/" + date.getCurrentDay() + "/" + date.getCurrentYear();
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date startDate = (Date) formatter.parse(s);
Please can you tell me how to do it ?
You don't need to format it. Just use this SQL Date Object instead of Date object from java.util package.
import java.sql.Date
// Creating a date object.
Date date = new Date();
In a database, make sure the data type of attribute 'date' is selected as "Date" also, not VarChar. Simply pass this sql package Date object into the database through query. :) It will save the date in a format.

JSON.NET: Get Specific JSON Date Value

In my VB.NET project, using JSON.NET, I've got a JSON from a Web API that has a value representing a date in the yyyy-MM-ddTHH:mm:ss format, and I'd like to simply get that value.
Here's more or less what the JSON looks like:
{
"REQ_DATE": "2016-01-17T12:27:57",
"REQ_TYPE": "Vacation",
"HOURS": 500.0,
"LEAVE_TIME": "8:00 AM",
"LEAVE_DATE": "2016-01-23T00:00:00",
"DUE_TIME": "8:00 AM",
"DUE_DATE": "2016-01-24T00:00:00",
}
So I should just serialize it and do what I will with the value, right? However, when I put that key-value in a variable, the date format is automatically changed!
Dim temp As String = myJsonResult("REQ_DATE")
' temp = "1/17/2016 12:27:57 PM"
I need to have that Date as it was from the retrieved JSON. I see two ways to go about this problem: converting it to yyyy-MM-ddTHH:mm:ss manually, or using regex to directly grab the key-value pair - both of which I have had no success with.
My attempt to convert it into DateTime:
Dim tempDateTime As DateTime = DateTime.ParseExact(myJsonResult("REQ_DATE").ToString,"yyyy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture)
' Error: String is not Recognized as valid DateTime
Dim myDesiredResult As String = tempDateTime.ToString("yyyy-MM-ddTHH:mm:ss")
My attempt to use Regex:
Dim regex As Regex = New Regex("""REQ_DATE"": ""([\d\w]*)""")
Dim match As Match = regex.Match(myJsonAsString)
If match.Success Then
Dim myDesiredResult As String = match.Groups(1).Value
End If
' match is empty...
Any and all help is greatly appreciated.
I assume that myJsonResult is a JObject into which you have loaded your JSON.
Your difficulty is that Json.NET automatically recognizes strings as dates when reading and converts them to DateTime structs. Then when you later do ToString() on the value token, it comes back in c#'s "invariant culture" format rather than the original format, which in this case was ISO 8601. If you do not want this behavior, you can parse your JSON using JsonSerializerSettings.DateParseHandling = DateParseHandling.None:
Dim jsonString = "{'REQ_DATE':'2016-01-17T12:27:57','REQ_TYPE':'Vacation','HOURS':500.0,'LEAVE_TIME':'8:00 AM','LEAVE_DATE':'2016-01-23T00:00:00','DUE_TIME':'8:00 AM','DUE_DATE':'2016-01-24T00:00:00'}"
Dim settings = New JsonSerializerSettings() With { _
.DateParseHandling = DateParseHandling.None _
}
Dim myJsonResult = JsonConvert.DeserializeObject(Of JObject)(jsonString, settings)
Dim dateValue = myJsonResult("REQ_DATE")
Dim dateString = CType(dateValue, String) 'Value is 2016-01-17T12:27:57
There's no overload to JObject.Parse() that takes a JsonSerializerSettings, so you would need to use DeserializeObject. This setting eventually gets propagated to JsonReader.DateParseHandling.
Alternatively, if you are OK with Json.NET recognizing dates but would always like them to be printed in ISO 8601 format, you can re-serialize the token to JSON rather than just getting the string value:
Dim dateValue = myJsonResult("REQ_DATE")
Dim dateString = JsonConvert.SerializeObject(dateValue).Trim(""""c) 'Value is 2016-01-17T12:27:57
Prototype fiddle. Related c# question.
When you get the parsed date-string from JSON.NET it will be in your culture's format as shown in your code comment:
Dim temp As String = myJsonResult("REQ_DATE")
' temp = "1/17/2016 12:27:57 PM"
That format is "M/d/yyyy HH:mm:ss tt" so use that format for parsing. But since it is in a format for your culture, you can let DateTime check/use all the known formats using TryParse:
Dim dt As DateTime
Dim temp As String = jobj("REQ_DATE").ToString
If DateTime.TryParse(temp, dt) Then
'dt is good to use!
Console.WriteLine(dt.ToString)
' Prints: 1/17/2016 12:27:57 PM
End If
Dim myDesiredResult As String = dt.ToString("yyyy-MM-ddTHH:mm:ss")
' result: "2016-01-17T12:27:57"
If you want to specify the format (it would be better to use TryParseExact):
dt = DateTime.ParseExact(temp, "M/d/yyyy HH:mm:ss tt",
CultureInfo.InvariantCulture)
Console.WriteLine(dt.ToString())
' Also prints: 1/17/2016 12:27:57 PM
Dates dont have a format, so it cant change, but it may display differently for your culture settings. You can display it any way you want, it is still the same date:
Console.WriteLine(dt.ToString("HH yyyy MM mm dd"))
Console.WriteLine(dt.ToString("yyyy-MM-ddTHH:mm:ss"))
Console.WriteLine(dt.ToString("MM/d/yyyy HH:mm:ss tt"))
Answering my own question. I've got it to work simply by doing DateTime.Parse on the JObject, then doing ToString to my desired format.
Dim temp As String = myRequest("REQ_DATE").ToString
Dim tempDateTime As DateTime = DateTime.Parse(temp.ToString)
Dim myDesiredResult As String = tempDateTime.ToString("yyyy-MM-ddTHH:mm:ss")
I used dbc's answer in my code as it is more elegant.

Grails insert date without time

I have a date attribute in my domain and I want to insert to MySQL without time. getting exception cannot cast string to date.Exception message:
Cannot cast object 2013-03-09 with class java.lang.String to class java.util.Date
I want to insert to the database without time.
Domain:
class Day {
Date date
static mappings = {
table name:'Days'
date type: 'date'
}
Controller:
def today = new Date()
def ymdFmt = new java.text.SimpleDateFormat("yyyy-MM-dd")
Date dateYmd = ymdFmt.format(today)
day.date =dateYmd
day.date = new Date().clearTime()
clearTime() will reset the time portion to 00:00:00
I think you wan't to look at Date.parse http://groovy.codehaus.org/groovy-jdk/java/util/Date.html#parse(java.lang.String, java.lang.String)
You can parse the date like.
String stringDate = '28/09/2010'
Date date = new Date().parse('d/M/yyyy', stringDate)
You should use java.sql.Date instead of java.util.Date.
The java.sql.Date class corresponds to SQL DATE which means it stores years, months and days while hour, minute, second and millisecond are ignored. Additionally java.sql.Date isn't tied to timezones.
For a good explanation about the two see java.util.Date vs java.sql.Date

Convert an object to a date

I have imported an xml file that contains a date stamp. I extracted the date stamp by placing it into an Object:
dataObject = new Object();
dataObject.date = ... etc.
The date stamp was created by a sql database and its structure is as follows, but it is no longer a Date:
2011-02-03 16:30:10
Can I convert the text in the Object back into a Date object within Flex to be able to use Date methods?
You can use Date::parse for this:
var date:Date = new Date(Date.parse(dateString));
However, note that Flash doesn't recognize "-" as a separator so you need to convert the string first. Something like this should work:
dateString = dateString.replace(new RegExp(/-/g), '/');
var date:Date = Date.parse(dateString);