Cannot Properly Transform Unix Timestamp to DateTime in Mule 4 - mule

So I am trying to convert a Unix Timestamp into a Human Readable date format (ex: January 20, 2021).
This is the response that I get from an API which gives the Unix timestamp
"time":1388620296020
And then I try to transform it using the Transform Message, my code looks like this
date: (object.properties.time as DateTime) as String {
format: "MMMM dd, yyyy"
},
But the output I get after I deploy it, goes like this
"date": "August 17, +45973"
I am not sure why is it happening.

Epoch can be directly converted to DateTime in Dataweave
Try This
date: (object.properties.time as DateTime {unit : "milliseconds"})
output:
"date": "2014-01-01T23:51:36.02Z"
You can check the output by entering in the below link as well
https://www.unixtimestamp.com/
https://www.epochconverter.com/

Another way to get the exact format,that you mentioned in the quesion (ex: January 20, 2021) it is achievable by below script
%dw 2.0
output application/json
---
date: payload.message as DateTime {unit : "milliseconds"}
as String {format: 'MMMM dd,yyyy'}
this script will give you output as:
{
"date": "January 01,2014"
}

Convert Unix Timestamp to Date Time in Mule 4
Input :
{
"time":1388620296020
}
---------output----------
{
"date": "01-Jan-2014 11:51:36"
}
How to write the script, You understand correct format Date Time.
%dw 2.0
output application/json
{
date: payload.time as DateTime {unit: "milliseconds"} as String {format: 'dd-MMM-yyyy hh:mm:ss'}
}
For more info referred link : https://help.mulesoft.com/s/question/0D52T00004tIkcf/how-to-convert-unix-timestamp-to-normal-human-readable-timestamp-using-dw-20
Thanks

Related

Reverse ordering in Mule4 using Date field

I wanted to do reverse ordering using Date field from highest to lowest (DSC). This question is similar to the below link Reverse ordering in Mule4. Thought small tweaks would make the fix. Tried various ways.Not working. When I try to format date it says the key cant be formatted to date or it complains about -. Any thoughts? Thanks
%dw 2.0
output application/json
var test = { "2022-10-19":[{"kio":"spotage"}] ,
"2022-10-17": [{"kio":"spotage"}] ,
"2022-10-18": [{"kio":"spotage"}]
}
---
test orderBy -($$ as String as Date {format: "yyyy-MM-dd"}
)
Expected Response:
{
"2022-10-19": [
{
"kio": "spotage"
}
],
"2022-10-18": [
{
"kio": "spotage"
}
],
"2022-10-17": [
{
"kio": "spotage"
}
]
}
The orderBy() function seems to be expecting a number to be able to do reverse sorting. A Date can not be converted directly to a number in DataWeave. However the date format 'yyyyMMdd' can be converted to a number that can directly sorted.
Example:
%dw 2.0
output application/json
var test = {
"2022-10-18":[{"kio":"spotage"}],
"2022-10-17": [{"kio":"spotage"}],
"2022-10-19": [{"kio":"spotage"}]
}
---
test orderBy -($$ as String as Date {format: "yyyy-MM-dd"} as String {format: "yyyyMMdd"} as Number)
I modified the input to show that the script actually orders the output.

Eventbrite giving response " wrong datetime format" on hitting event/ endpoint

I am writing a script in python to create an event.Newbie at this.Below is the entire script code for reference.
import requests,json
from datetime import datetime
event={}
event['name']={}
print("Enter the following:\ntitle of event")
event['name']['html']=input()
event['description']={}
event['description']['html']=input("Event description:\n")
event['start']={}
startdate=datetime.strptime(input("start datetime eg :Jun 1 2005 1:33PM :\n"),'%b %d %Y %I:%M%p')
event['start']['utc']=str(startdate.date())+'T'+str(startdate.time())+'Z'
#event['start']['utc']=startdate.isoformat()+"Z"
#Turning datetime in YYYY-MM-DDThh:mm:ssZ format
event['start']['timezone']=input("timezone eg Asia/kolkata\n")
event['end']={}
enddate=datetime.strptime(input("end datetime eg :Jun 1 2005 1:33PM\n"),'%b %d %Y %I:%M%p')
event['end']['utc']=str(enddate.date())+'T'+str(enddate.time())+'Z'
#event['end']['utc']=enddate.isoformat()+"Z"
event['end']['timezone']=event['start']['timezone']
event['currency']=input("3 letter code")
response = requests.post("https://www.eventbriteapi.com/v3/events/",
headers = {
"Authorization": "Bearer NC.....",
"Content-Type" : "application/json"
},
data=json.dumps({"event":event}),
verify = True, # Verify SSL certificate
)
Strictly followed the docs https://www.eventbrite.com/developer/v3/endpoints/events/
According to docs datatype of event.start.utc and event.start.end data shall be datetime i.e "2010-01-31T13:00:00Z"
We can see in the comments I also tried with isoformat function.
On printing event object I found the same format as specified in the docs.
But receiving response.content as event.start invalid argument or event.start.utc as datetime wrong format use instead "YYYY-MM-DDThh:mm:ssZ" !!
I ran into date issues with Eventbrite too; after debugging found this to work for events:
{ event:
{ name: { html: 'Postman API Event!' },
description:
{ html: 'My fav event is The Winter Formal.' },
start: { timezone: 'America/Los_Angeles', utc: '2018-09-06T00:19:53Z' },
currency: 'USD',
listed: false,
end: { timezone: 'America/Los_Angeles', utc: '2018-09-06T00:20:53Z' } } }
and of course, different date formats in another part of API ;-)
Regarding discounts / cross event discount, where the docs specify a
Naive Local ISO8601 date and time format
First I've heard of the 'Naive' format? Why no example Eventbrite? Here's what worked:
2018-10-11T12:13:14

date operations in mule esb using data weave

I have requirement like where need to find difference in between two dates using dataweave, Both input and output is XML format.
both the date formats are yyyy.mm.dd and output date format must be like mm.dd.yy or mm.dd.yyyy.
Please assist me, thanks
You can format dates like this (example):
yourInputDate as :localdatetime {format: "yyyy-MM-dd'T'HH:mm:ss"})
you can add and subtract dates, another example how i use this in a project with variables:
%var stamp = (now as :localdatetime {format: "yyyy-MM-dd'T'HH:mm:ss"})
%var dayDiff = ("P" ++ (stamp.dayOfWeek - 1) ++ "D") as :period
%var firstDateWeek = (stamp - dayDiff) as :localdatetime {format: "yyyy-MM-dd"}
docs here: https://docs.mulesoft.com/mule-user-guide/v/3.8/dataweave-types#datetime
In Dataweave, you can convert a string to date format and then just subtract them
Input
<dates>
<startDate>2007.05.01</startDate>
<endDate>2017.02.15</endDate>
</dates>
Transform
%dw 1.0
%var startDate = payload.dates.startDate as :date {format: "yyyy.MM.dd"}
%var endDate = payload.dates.endDate as :date {format: "yyyy.MM.dd"}
%output application/json
---
{
difference: startDate - endDate
}
Output
{
"difference": "P9Y9M14D"
}
9 years, 9 months, 14 days
You can create a global function with Java/Groovy and use DateTime object to find the difference and return from that function. Now you can use that function inside your dataweave.
Subtracting two Dates in dataweave. Format the date according to your requirement
%dw 1.0
%output application/json
---
{
a: |23:59:56-03:00| - |22:59:56-00:00|,
b: |2003-10-01| - |2002-09-23|
}
{
"a": "PT-4H",
"b": "P-1Y-8D"
}

How to parse this time string with Datatables and moment.js?

So I'm using datatables and their moment.js plugin (https://datatables.net/plug-ins/dataRender/datetime). I always get (the string) "Invalid date" returned...
{ "data": "last_updated", //source: 2016-11-02 10:32pm GMT
render: $.fn.dataTable.render.moment( 'YY-MM-DD hh:mmtt GMT', 'DD MMM YY' )
}
Thanks!
That plugin takes one, two or three arguments. From testing it seems as though your date is valid so I'd suggest just passing "SS MMM YY" to the function. As a quick example this seems to work:
moment("2016-11-02 10:32pm GMT").format("DD MMM YY"); // "02 Nov 16"
Another issue might be that the date isn't set, so it's perhaps worth checking for nulls and setting some default content. In fact, if you've already got momentjs available you can replace the plugin with this as the render function:
"render": function(data){
return (moment(data).isValid()) ? moment(data).format("DD MMM YY") : "-";
}
Hope that helps.

Logstash: modify apache date format

The grok-filter %{COMBINEDAPACHELOG} formats the timestamp as dd/MMM/YYYY:HH:mm:ss Z however I need the timestamp in the format of yyyy-MM-dd HH:mm:ss
I tried the below configuration
grok {
match => [
"message", "%{COMBINEDAPACHELOG}",
]
break_on_match => false
}
date {
match => [ "timestamp", "yyyy-MM-dd HH:mm:ss" ]
target => ["datetime"]
}
but got the below parsing error:
Failed parsing date from field {:field=>"timestamp", :value=>"19/May/2012:12:40:18 -0700", :exception=>java.lang.IllegalArgumentException: Invalid format: "19/May/2012:12:40:18 -0700" is malformed at "/May/2012:12:40:18 -0700", :level=>:warn}
Would highly appreciate if anyone can throw more light on the same.
The COMBINEDAPACHELOG pattern is expecting the date in the log entry to match the format so it can shove it into the "timestamp" field. It doesn't format your timestamp at all.
Once the date has been grok'ed out into "timestamp", you can use the date{} filter to move it into #timestamp. The pattern you supply there should match whatever's in the field.
So, pass "dd/MMM/yyyy:HH:mm:ss Z" as the format to date{} and you should be all set.
EDIT:
Based on your additional details, I was hoping that you could match each component of the input date and then combine them into a new field. That would work if you were trying to swap, say, firstName and lastName in a string, but dates are more complicated. A simple string swap wouldn't handle converting "Jan" to "01" or deal with timezones at all.
So, we're back to creating a date object and then outputting that as a string in the format you desire.
# convert "timestamp" to a date field "datetime"
date {
match => [ "timestamp", "dd/MMM/yyyy:HH:mm:ss Z" ]
target => ["datetime"]
}
# convert "datetime" to a string "datestring"
ruby {
code => "
event['datestring'] = event['datetime'].strftime('%Y-%m-%d %H:%M:%S')
"
}
For the latest version of Logstash the code would be:
# convert "datetime" to a string "datestring"
ruby {
code => "event.set('datestring', event.get('datetime').strftime('%Y-%m-%d %H:%M:%S'))"
}