JSON string to date with Javascript in Google Apps Script editor - json

I am working through w3schools, particularly https://www.w3schools.com/js/js_json_parse.asp
I ran this example and got an unexpected result
let dashText = '{ "name":"John", "birth":"1986-12-14", "city":"New York"}';
let objD = JSON.parse(dashText);
console.log("objD: ", objD);
objD.birth = new Date(objD.birth);
console.log("objD.birth: ", objD.birth);
3:09:04 PM Info objD: { name: 'John', birth: '1986-12-14', city: 'New York' }
3:09:04 PM Info objD.birth: Sat Dec 13 1986 18:00:00 GMT-0600 (Central Standard Time)
Note the difference in the dates. I then changed the dashes to slashes out of curiosity and the date was correctly determined from the string.
let slashText = '{ "name":"John", "birth":"1986/12/14", "city":"New York"}';
let objS = JSON.parse(slashText);
console.log("objS: ", objS);
objS.birth = new Date(objS.birth);
console.log("objS.birth: ", objS.birth);
3:09:04 PM Info objS: { name: 'John', birth: '1986/12/14', city: 'New York' }
3:09:04 PM Info objS.birth: Sun Dec 14 1986 00:00:00 GMT-0600 (Central Standard Time)
Can anyone explain the results?

Javascript parses DateTime strings differently based on how the string is formatted. The dashes are parsed to ISO date, i.e. international time. You can see this when it tries to handle the timezone conversion, where it sets the time to 18:00:00 to account for the 6 hour shift from Universal Time. Slashes are parsed as just the date, and doesn't try to adjust the time based on timezones.
Here's a w3schools link that goes over this in more detail.

Related

Unable to process JSON input when ingesting logs to Oracle

Error:
send: b'{"specversion": "1.0", "logEntryBatches": [{"entries": [{"data": "{\\"hello\\": \\"oracle\\", \\"as\\": \\"aaa\\"}", "id": "ocid1.test.oc1..jkhjkhh23423fd", "time": "2021-04-01T12:19:28.416000Z"}], "source": "EXAMPLE-source-Value", "type": "remediationLogs", "defaultlogentrytime": "2021-04-01T12:19:28.416000Z"}]}'
reply: 'HTTP/1.1 400 Bad Request\r\n'
header: Date: Fri, 02 Apr 2021 07:39:16 GMT
header: opc-request-id: ER6S6HDVTNWUOKCJ7XXZ/OpcRequestIdExample/770899C2C7CA6ABA11D996CC57E8EE8F
header: Content-Type: application/json
header: Connection: close
header: Content-Length: 79
Traceback (most recent call last):
File "tool.py", line 45, in <module>
put_logs_response = loggingingestion_client.put_logs(
File "/home/ubuntu/.local/lib/python3.8/site-packages/oci/loggingingestion/logging_client.py", line 172, in put_logs
return self.base_client.call_api(
File "/home/ubuntu/.local/lib/python3.8/site-packages/oci/base_client.py", line 276, in call_api
response = self.request(request)
File "/home/ubuntu/.local/lib/python3.8/site-packages/oci/base_client.py", line 388, in request
self.raise_service_error(request, response)
File "/home/ubuntu/.local/lib/python3.8/site-packages/oci/base_client.py", line 553, in raise_service_error
raise exceptions.ServiceError(
oci.exceptions.ServiceError: {'opc-request-id': 'ER6S6HDVTNWUOKCJ7XXZ/OpcRequestIdExample/770899C2C7CA6ABA11D996CC57E8EE8F', 'code': 'InvalidParameter', 'message': 'Unable to process JSON input', 'status': 400}
I am trying to send json data to Oracle logs, but getting the above error. I am using json.dumps(data) to convert the dict to string. Kindly let me know if any workaround available to this.
Code:
data = {'hello':'oracle', "as":"aaa"}
put_logs_response = loggingingestion_client.put_logs(
log_id="ocid1.log.oc1.iad.<<Log OCID>>",
put_logs_details=oci.loggingingestion.models.PutLogsDetails(
specversion="1.0",
log_entry_batches=[
oci.loggingingestion.models.LogEntryBatch(
entries=[
oci.loggingingestion.models.LogEntry(
data= json.dumps(data),
id="ocid1.test.oc1..jkhjkhh23423fd",
time=datetime.strptime(
"2021-04-01T12:19:28.416Z",
"%Y-%m-%dT%H:%M:%S.%fZ"))],
source="EXAMPLE-source-Value",
type="Logs",
defaultlogentrytime=datetime.strptime(
"2021-04-01T12:19:28.416Z",
"%Y-%m-%dT%H:%M:%S.%fZ"))]),
timestamp_opc_agent_processing=datetime.strptime(
"2021-04-01T12:19:28.416Z",
"%Y-%m-%dT%H:%M:%S.%fZ"),
opc_agent_version="EXAMPLE-opcAgentVersion-Value",
opc_request_id="ER6S6HDVTNWUOKCJ7XXZ/OpcRequestIdExample/")
This exception indicates that you have an InvalidParameter in your JSON input.
oci.exceptions.ServiceError: {'opc-request-id': 'ER6S6HDVTNWUOKCJ7XXZ/OpcRequestIdExample/770899C2C7CA6ABA11D996CC57E8EE8F', 'code': 'InvalidParameter', 'message': 'Unable to process JSON input', 'status': 400}
The InvalidParameter is your timestamp, which is date - 2021-04-01T12:19:28.416Z.
According to Oracle's documentation you need to use a RFC3339-formatted date-time string with milliseconds precision when creating a LogEntry.
This code snippet is from oci-python-sdk - log_entry.py, but it doesn't mention the milliseconds precision like Oracle's documentation.
#time.setter
def time(self, time):
"""
Sets the time of this LogEntry.
Optional. The timestamp associated with the log entry. An RFC3339-formatted date-time string.
If unspecified, defaults to PutLogsDetails.defaultlogentrytime.
:param time: The time of this LogEntry.
:type: datetime
"""
self._time = time
This code create a UTC RFC3339 complaint timestamp with milliseconds precision
from datetime import datetime
from datetime import timezone
current_utc_time_with_offset = datetime.now(timezone.utc).isoformat()
print(current_utc_time_with_offset)
#output
2021-04-06T13:00:52.706040+00:00
current_utc_time_with_timezone = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
print(current_utc_time_with_timezone)
#output
2021-04-06T13:09:10.053432Z
This Stack Overflow question is worth a read:
What's the difference between ISO 8601 and RFC 3339 Date Formats?
This article is also useful:
Understanding about RFC 3339 for Datetime and Timezone Formatting in Software Engineering
Your data looks fine , I think the issue is that Time precision is more than millisec. it should work fine if you loose the trailing zeros in time.
Format a datetime into a string with milliseconds
https://docs.oracle.com/en-us/iaas/api/#/en/logging-dataplane/20200831/LogEntry/
Your time is RFC3339 but precision is more than millisec
'{"specversion": "1.0", "logEntryBatches": [{"entries": [{"data": "{\"hello\": \"oracle\", \"as\": \"aaa\"}", "id": "ocid1.test.oc1..jkhjkhh23423fd", "time": "2021-04-01T12:19:28.416000Z"}], "source": "EXAMPLE-source-Value", "type": "remediationLogs", "defaultlogentrytime": "2021-04-01T12:19:28.416000Z"}]}'
See https://docs.oracle.com/en-us/iaas/api/#/en/logging-dataplane/20200831/LogEntry/
The timestamp associated with the log entry. An RFC3339-formatted date-time string with milliseconds precision. If unspecified, defaults to PutLogsDetails.defaultlogentrytime.

How to render correct datetime in hugo post?

I created a post using hugo new posts/mypost.md and it created mypost.md for me with header toml configuration like that
But, when i run on server (local), the datetime rendered wrong like:
How can I fix that?
Thanks in advance!
This is how I got it to work:
Add your date format in config.toml
[params]
dateFormat = "02 Jan 2006"
Your post should contain the date in its front-matter:
---
date: "2020-12-23T15:21:54+05:30"
...
---
Use the format in your layout:
<div>{{ .Params.date.Format .Site.Params.dateFormat }}</div>
Note: Please DO NOT change the numbers in the date format. It must be 02 for day, Jan for month, 2006 for year, etc. check this for more details.
Check also Hugo 0.87 (Aug. 2021, two years later), which comes with:
a timezone
a timedate format
{{ time.Format "Monday, Jan 2, 2006" "2015-01-21" }}
→
"Wednesday, Jan 21, 2015"
Note that since Hugo 0.87.0, time.Format will return a localized string for the current language.
Date/time formatting layouts
{{ .Date | time.Format ":date_long" }}
The full list of custom layouts with examples for English:
:date_full => Wednesday, June 6, 2018
:date_long => June 6, 2018
:date_medium => Jun 6, 2018
:date_short => 6/6/18
:time_full => 2:09:37 am UTC
:time_long => 2:09:37 am UTC
:time_medium => 2:09:37 am
:time_short => 2:09 am
In Hugo v0.95.0 (released 16 Mar 2022), it should be
[params]
date_format = "02 Jan 2006"
with
---
date: 2022-03-18T21:10:00+07:00
---
in the post front matter, where double quote marks are not necessary. I used Ananke theme.
Setting the date_format in the config file seems weird to me. I would set the following in the config file:
defaultContentLanguage: nl
languageCode: nl_NL
These are variables that do NOT go into params, but on the root level of the config file. When you have these you can simply call:
{{ .Date | time.Format ":date_long" }}
or... if you need another format:
{{ .Date | time.Format ":date_medium" }}
The date will be formatted in your language.
You need to set dateformat in file config.toml at 2.1.2006 (any proper format, ensure 2, Jan, 2006).
This link save my day

Change date format in my HTML / CSS output

Have a dates saved in my sqlite database in this format 2019-01-24 13:41:40.515955 and when I output to my web page its displayed as 2019-01-24 13:41:40 UTC. Please can I get guidance on displaying something like Wed 24 January 2019 ? No sure how to approach it
Use Javascript, would be a simple approach to parse and format dates with desired output.
var date = new Date('6/29/2011 4:52:48 PM UTC');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"
var date = new Date('6/29/2011 4:52:48 PM UTC');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"
console.log(`Year: ${date.getFullYear()}, Month: ${date.getMonth()}, Day, ${date.getDay()}`)
You can also parse dates using Date.parse(``);

Json set Date Format - Print timestamp and epoch time both

I am using objectmapper.enable(SerializationFeature.INDENT_OUTPUT).writerWithDefaultPrettyPrinter().writeValueAsString(r);
Result: "begin" : 1513644267698,
which returns the values in the object 'r' and the time in epoch format as stored. I now wish to print the time in a readable format, so i did the following change:
DateFormat df = new SimpleDateFormat(dateFormat);
return myMapper.setDateFormat(df).enable(SerializationFeature.INDENT_OUTPUT).writerWithDefaultPrettyPrinter().writeValueAsString(r);
Here i can pass the required dateFormat and print it in my desired format for eg. "EEE MMM dd, yyyy HH:mm:ss.SSS (z)".
Result: "begin" : "Tue Feb 20, 2018 09:02:24.941 (UTC)",
My question is - is there any way where i can print both epoch time and the above time format together in the same.
Required Result: "updatedTime" : [1513644267698] Tue Feb 20, 2018 09:02:24.941 (UTC),

finding the d3.extent of an array with dates to create xScale in D3

I am trying to create a focus brush, similar to this http://bl.ocks.org/mbostock/1667367, using a json file.
I am having a problem to correctly read the date and create the xScale for the chart.
Say these are some of the dates in my Json file, extracted into an array.
//some dates
dates = ["Fri Jul 27 22:32:59 2012","Fri Jul 27 22:33:59 2012","Fri Jul 27 22:34:59 2012","Fri Jul 27 22:35:59 2012","Fri Jul 27 22:36:59 2012"];
//declare new date variable
var dates2 =[];
var format = d3.time.format("%a %b %d %H:%M:%S %Y");
dates.forEach(function(d){
dates2.push(format.parse(d));
});
console.log(d3.extent(dates_extents));
dates_extents = d3.extent(dates2);
x.domain(d3.extent(dates_extents);
x2.domain(x.domain);
Althought the dates_extents is printed in the console, I get this error:
TypeError: n.map is not a function [Break On This Error] ...t,n)},n.copy=function(){return ae(t)},n}function oe(t){return t.innerRadius}func... d3.v3.min.js (line 1)
Any ideas what might be the source of the problem and how I can solve it?
Thanks!