JSON.NET: Get Specific JSON Date Value - json

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.

Related

Convert JSON date to vb.net date format

Following is the vb.net code which reads json string and then it bulkcopy to SQL.
I am getting and error when it bulkcopy to sql server saying "Invalid Data type"
Issue is with date format of column ("idt"). If i don't include this column in SQLBulk copy then it successfully inserts rest of the data into SQL.
Dim JsonP As JObject = JObject.Parse(decodedString)
Dim SetPointerOut As JToken = JsonP("b2b")
Try
Dim i as Integer = 0
Dim j as Integer = 0
For Each itemout as Object In SetPointerOut
Dim SetPointerIn As JToken = JsonP("b2b")(i)("inv")
For Each itemin as Object In SetPointerIn
Dim SetPointerInSub As JToken = JsonP("b2b")(i)("inv")(j)("itms")
For Each iteminsub as Object In SetPointerInSub
Dim NewDRinsub As DataRow = TempDT.NewRow
NewDRinsub("ctin") = itemout("ctin")
NewDRinsub("cfs") = itemout("cfs")
NewDRinsub("val") = itemin("val")
NewDRinsub("inv_typ") = itemin("inv_typ")
NewDRinsub("pos") = itemin("pos")
NewDRinsub("idt") = itemin("idt") --- **source json has this date in format "dd-mm-yyyy"
NewDRinsub("rchrg") = itemin("rchrg")
NewDRinsub("inum") = itemin("inum")
NewDRinsub("chksum") = itemin("chksum")
TempDT.Rows.Add(NewDRinsub)
Next
j = j + 1
Next
i += 1
j = 0
Next
Using sqlBulkCopy As New SqlBulkCopy(Mycon.mConnection, SqlBulkCopyOptions.FireTriggers, Nothing)
sqlBulkCopy.DestinationTableName = "GST2_B2B"
sqlBulkCopy.ColumnMappings.Add("ctin", "PartyGSTNo")
sqlBulkCopy.ColumnMappings.Add("cfs", "CFS")
sqlBulkCopy.ColumnMappings.Add("val", "Invoice_Value")
sqlBulkCopy.ColumnMappings.Add("inv_typ", "Invoice_Type")
sqlBulkCopy.ColumnMappings.Add("pos", "StateCode")
sqlBulkCopy.ColumnMappings.Add("idt", "Invoice_Date") --- source json has this date in format "dd-mm-yyyy"
sqlBulkCopy.ColumnMappings.Add("rchrg", "ReverseCharge")
sqlBulkCopy.ColumnMappings.Add("inum", "Invoice_Number")
sqlBulkCopy.ColumnMappings.Add("chksum", "CHKSUM")
sqlBulkCopy.ColumnMappings.Add("period", "Period")
sqlBulkCopy.BulkCopyTimeout = 120
sqlBulkCopy.WriteToServer(TempDT) -- error at this stage
--- Getting error at this stage, saying "Invalid datatype", and that is because of column sqlBulkCopy.ColumnMappings.Add("idt", "Invoice_Date")
End Using
so as said, if i remove sqlBulkCopy.ColumnMappings.Add("idt", "Invoice_Date"), then it works well. I guess Bulkcopy has some issue with dateformt of "idt" column of vb.net datatable.
So, how do i resolve this dateformat issue?
how do i convert json date to vb.net format at code line marked above with comment?
Just for grins give this a shot.
NewDRinsub("idt") = Date.ParseExact(itemin("idt"), "dd-MM-yyyy", CultureInfo.InvariantCulture)
https://learn.microsoft.com/en-us/dotnet/api/system.datetime.parseexact?view=netframework-4.8#System_DateTime_ParseExact_System_String_System_String_System_IFormatProvider_

How can I get the timestamp in “yyyy/MM/dd hh:mm:ss.fff"” format in VBA?

I want to get this output:
2018-09-02 00:00:00.000
I tried the below code:
.Cells(LRS + 1, 15).Value = Format(.Cells(LRS + 1, "A").Value, "yyyy-MM-dd hh:mm:ss.fff")
And I got:
2018-09-02 00:00:00.fff
The initial date in Excel has the following format yyyy/mm/dd, no time included. That's why the time part includes only zeros 00:00:00.000. The reason I want to include the time in the specific format is that I'm planning to import those dates into a SQL table with that format.
Is there any solution?
As you can see from the documentation fff is not recognised as a formatting token in VBA.
Helpfully, you can actually import your data into SQL without formatting it to add the time. If you import it into a datetime field the SQL engine will automatically default the time part of the field to midnight on the date you give it.
I think you can just change your format string to yyyy-MM-dd by itself.
However if you really want to do it like this, then since there's no time specified then just hard-code 000 instead of fff. The rest of the time can be similarly hard-coded, since it never varies, so you end up with yyyy-MM-dd 00:00:00.000. But as I said, I think it's a bit pointless.
After replacing the cell format with the corresponding format, it is likely that the value of the cell is imported as text, not as a value.
Sub test()
Dim s As String, s1 As String, s2 As String
'First Cell format as your "yyyy-mm-dd hh:mm:ss.000"
Range("a2").NumberFormatLocal = "yyyy-mm-dd hh:mm:ss.000"
'In vb,This format("yyyy-mm-dd hh:mm:ss.000") is not recognized.
Range("b2") = Format(Range("a2"), "yyyy-mm-dd hh:mm:ss.000")
s1 = Format(Range("a2"), "yyyy-mm-dd hh:mm:ss.000")
's1 = "2018-09-03 01:24:33.000"
'Since you format a2 cell as "yyyy-mm-dd hh:mm:ss.000" you can get data as text
Range("b2") = Range("a2").Text
s2 = Range("a2").Text
's2= "2018-09-03 01:24:33.240"
End Sub
Sheet Data
Local Window

How to convert an Image into BLOB (Binary Large Object) format

I need a comparison between an input image with the
blob field in MySql table. so that i need to conver the image into BLOB format.
i had tried a lot in previous days but faild to achieve a good,i here by summerise the result
of my search for this comparison:
convert the image into byte array using the following code
Dim fileName As String
ListBox1.Items.Clear()
fileName = "D:\me.jpeg"
Dim fs As New FileStream(fileName, FileMode.Open, FileAccess.Read)' Create a byte array of file stream length
Dim ImageData As Byte() = New Byte(fs.Length - 1) {}'Read block of bytes from stream into the byte array
fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length))'Close the File Stream
fs.Close()
For j As Integer = 0 To ImageData.Length - 1
ListBox1.Items.Add(ImageData(j).ToString)' list out the byte array
Next
Retrive the blob field carasponds to the same field
ListBox1.Items.Clear()
mystring = "select image from blob_table where id='28' "
openconnection() ' Methode to open a mysql connection
cmd = New Odbc.OdbcCommand(mystring, myconnection)
imagebyte = cmd.ExecuteScalar
For j As Integer = 0 To imagebyte.Length - 1
ListBox2.Items.Add(imagebyte(j).ToString) ' list out the BOLB array
Next
closeconnection() ' Close the connection
Both the list boxes are shown in the image below.
Both the lists are entirely different, byte array is comparitevely very large than blob it having more than 10K values so the comparison become harder and does not give the expected result.
Is their any possibility to convert an image into blob format? through vb.net. or any other
alternate solution for this comparison
Thanks in Advance for positive response....!

Scala date formatting from 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.

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