I am trying to convert Unix time stamp into date
final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
final String startdate = Instant.ofEpochSecond(Long.parseLong(requestVO.getStartDate().toString()))
.atZone(ZoneId.of("GMT-4"))
.format(formatter);
final String enddate = Instant.ofEpochSecond(Long.parseLong(requestVO.getEndDate().toString()))
.atZone(ZoneId.of("GMT-4"))
.format(formatter);
above is what I have tried for the format of date Mentioned in DateTimeFormatter and requestVO.getStartDate() is giving Date type value.I am applying the startDate and endDate in sql query Like below
and ceo.erx_date between '"+startdate+"' and '"+enddate+"'
No compilation errors getting But, giving number format exception.
If requestVo.getStartDate() returns a Date object, your error is here:
Long.parseLong(requestVo.getStartDate())
As the documentation says, Long.parseLong(String) throws
NumberFormatException - if the string does not contain a parsable long.
Try this:
Long.parseLong(requestVo.getStartDate().getTime())
In every case two things:
Take care from NullPointerException: check if your date is null or not
Use preparedStatement and not string concatenation when write e query in Java
There are at least two reasons to use PreparedStatement instead of Statement:
They are faster then simple Statement: because Statement are compiled and execute every time, but PreparedStatment are compiled once
In case of PreparedStatement you are safe from the point of view of SQL injection
tl;dr
myJavaUtilDate // The terrible `java.util.Date` class is the legacy way to represent a moment in UTC.
.toInstant() // `Instant` is modern way to represent a moment in UTC.
.atZone( // Adjust from UTC to some time zone.
ZoneId.of( "America/Martinique" ) // Specify the time zone you had in mind for an offset of four hours behind UTC.
) // Returns a `ZonedDateTime` object.
.format( // Generate text representing the value of our `ZonedDateTime` object's content.
DateTimeFormatter.ISO_LOCAL_DATE_TIME // A predefined formatter per ISO 8601 that omits any indication of time zone or offset-from-UTC.
)
.replace(
"T" , // Standard ISO 8601 formats use a `T` between the date and time-of-day portions.
" "
) // Returns a `String`.
java.util.Date::toInstant
requestVO.getStartDate() is giving Date type value.
You are working too hard.
Convert the terrible Date class object to its modern replacement, Instant. Notice how the legacy classes were given new methods for conversion to/from the modern java.time classes. Look for to… & from… methods on the old classes. In this case, Date::toInstant.
Instant instant = myJavaUtilDate.toInstant() ;
Zone versus offset
.atZone(ZoneId.of("GMT-4"))
Nope, -4 is not a time zone. That is an offset.
An offset-from-UTC is merely a number of hours-minutes-seconds ahead or behind the prime meridian.
A time zone is much more. A time zone is a history of the past, present, and future changes in offset used by the people of a particular region. A time zone carries a name in format of Continent/Region such as Asia/Kolkata or Pacific/Auckland.
Better to use a time zone than a mere offset. For one thing, you may be wrong about the offset. By using an time zone, java.time will determine the offset in effect at your intended moment.
Zone for offset of four hours behind UTC
Perhaps by -4 you have in mind a time zone such as America/Martinique, America/Aruba, or America/Puerto_Rico.
ZoneId z = ZoneId.of( "America/Puerto_Rico" ) ;
Instant + ZoneId ➡ ZonedDateTime
Apply that ZoneId to produce a ZonedDateTime object. Same moment, different wall-clock time.
ZonedDateTime zdt = instant.atZone( z ) ;
Generating text
Produce a string in standard ISO 8601 format, wisely extended to append the name of the zone in square brackets.
String output = zdt.toString() ;
But you wanted a format similar to ISO 8601, but without the T in the middle and with no indicator of offset/zone. I do not recommend reporting a moment without representing the time zone or offset. But if you insist:
String output =
zdt
.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " )
;
Related
When i fetch date from Oracle i add inline query in my server code as ,
cast((CURRENT_TIMESTAMP AT TIME ZONE 'Europe/Amsterdam') AS DATE)
The same above format how to implement to the below code,
dim currentDate as datetime= DateTime.Now
Regards
Sangeetha
The Oracle code shown gets the current date and time in Amsterdam, and truncates the time by casting it to a DATE type.
The equivalent VB.Net code would be:
Dim dt as Date
dt = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.UtcNow, "W. Europe Standard Time").Date
Note the .Date at the end. That sets the time portion to zero, similar to how you were truncating the time in Oracle. If you don't want that, then leave .Date off.
This also assumes you're running on Windows. If you're running .NET on a non-Windows platform, then you can use the same string as you did on oracle, "Europe/Amsterdam".
I am having an OData Service returning some DateTime values. They are saved in a table in the back end as TIMESTAMPL (with some other data).
Now there is the value 20160630084459.5000. With MOVE-CORRESPONDING into the et_entityset, where it is a TIMESTAMP. Because of the rounding, it gets 20160630084460, Since a the seconds must be between 00 and 59, this is not a valid value to return.
My main problem is, that my table has extremely much entries, so I need a performant way to fix this error.
Here is a way to convert it to what you want.
REPORT zzy NO STANDARD PAGE HEADING.
FORM convert_timestamp.
DATA(l_t1) = CONV timestampl('20160630084459.5000').
DATA: l_t2 TYPE timestamp.
l_t2 = l_t1.
WRITE / : l_t1, l_t2.
CONVERT TIME STAMP l_t1 TIME ZONE sy-zonlo INTO DATE DATA(l_date) TIME DATA(l_time).
CONVERT DATE l_date TIME l_time INTO TIME STAMP l_t2 TIME ZONE sy-zonlo.
WRITE / l_t2.
ENDFORM.
START-OF-SELECTION.
PERFORM convert_timestamp.
Here is the output.
20.160.630.084.459,5000000
20.160.630.084.460
20.160.630.084.459
You mention floor in your question but that is not what is happening. The value is rounded. If you simple do use FLOOR in your assignment from TIMESTAMPL to TIMESTAMP you will get the answer you want. If you have to use MOVE-CORRESPONDING, just do that first and then do a seperate assignment for the timestamp.
However, this means that 0:59.9 will get translated to 0:59 and not 1:00. If that missing second is OK for your application then just use the FLOOR command. If not it becomes more complicated and you will take a performance hit.
I am running a query between several tables and I am running into an issue between comparing two time columns on separate tables: "rc1_time" is in a string format and "osemplog_time" is in a time format. both are time only with no date
rc1_time's contents look like this '10560684' which corresponds to HH24MISSMS
osemplog_time's contents look like 07:57:02.917455
how do I format the rc1_time into a "time format" with no date?
what are some options for comparing the two times?
I am newbie at this exposition on your answers would be welcome
below is my query
SELECT
"public".payroll_master.prm1_name,
"public".payroll_master.prm1_oe_init,
"public".receipt.rc1_init,
"public".employee_log.osemplog_ipaddress,
"public".employee_log.osemplog_event,
"public".receipt.rc1_date,
"public".employee_log.osemplog_logdate,
"public".receipt.rc1_code,
"public".employee_log.osemplog_logname,
"public".oslogname.lognm_empname,
"public".receipt.rc1_arname,
"public".receipt.rc1_arnum,
"public".receipt.rc1_time,
"public".employee_log.osemplog_logtime
FROM
"public".receipt
INNER JOIN "public".employee_log ON "public".receipt.rc1_date = "public".employee_log.osemplog_logdate
INNER JOIN "public".payroll_master ON "public".payroll_master.prm1_oe_init = "public".receipt.rc1_init
INNER JOIN "public".oslogname ON "public".oslogname.lognm_empname = "public".payroll_master.prm1_name AND "public".oslogname.lognm_name = "public".employee_log.osemplog_logname
WHERE
"public".receipt.rc1_code = 'CA'
AND
"public".employee_log.osemplog_logdate = "public".receipt.rc1_date
ORDER BY
"public".receipt.rc1_init ASC
Question as stated
You can represent a time without a date using the time data type. To convert a string from a given format into one, you can go through the to_timestamp function and then cast to time:
SELECT to_timestamp('10560684', 'HH24MISSUS')::time;
SELECT to_timestamp('07:57:02.917455', 'HH24:MI:SS.US')::time;
The basic idea is that you parse the time string using to_timestamp. The resulting timestamp will have a default date, and casting to time will remove the date, leaving only the parsed out time portion.
Assumptions:
Your hours are in 24-hour clock format (13-23 for 1 PM to 11 PM and 00 for midnight). If they are not 24 hour times, then you are missing the AM/PM designation and will need to sort that out.
The second "SS" you mention in your first pattern is actually a fractional part of seconds. If not, you'll need to adjust the pattern. If you don't care about the fractional seconds, you might consider just leaving the US and the .US off entirely and working only at the seconds level. Note that US interprets 84 to be 0.84 seconds, not actually 84 microseconds (0.000084 seconds).
Ultimately, you will need to either provide much more precise details about the format or figure out the correct format string yourself. Rather than worry about those details, I've tried to exemplify the general mechanism and leave those to you.
Comparison is then trivial. You just use PostgreSQL's operators (<, >, =, etc.):
SELECT to_timestamp('07:57:02.917455', 'HH24:MI:SS.US')::time < to_timestamp('10560684', 'HH24MISSUS')::time;
Other considerations
Be aware of time zone issues if you are working across them. You'll want to look at timetz (short form of time with time zone) or timestamptz (short form of timestamp with time zone) if you need to deal with time zones. Generally, I would recommend including time zone handling up front in case it becomes a problem later.
In this case, why not build a complete timestamp? You already have the dates: "public".receipt.rc1_date and "public".employee_log.osemplog_logdate.
You don't specify the data types, but whatever the forms of those are, it should be possible. For example, if they are actual date objects, then:
SELECT to_timestamp(to_char("public".receipt.rc1_date, 'YYYY-MM-DD')||' '||"public".receipt.rc1_time, 'YYYY-MM-DD HH24MISSMS');
If they are strings of the form 'YYYY-MM-DD', then:
SELECT to_timestamp("public".receipt.rc1_date||' '||"public".receipt.rc1_time, 'YYYY-MM-DD HH24MISSMS');
And so on. Now you have a real timestamp, which makes simple great/less than comparison much, much easier.
In my experience, it's extremely rare that you actually want to test time stamps with fractional second precision for equality. You might want a more tolerant equality check, something like SELECT t1 - t2 < interval '5 seconds', but this is really up to the application.
Iam new to Pig and I have a sample test data of 500 KB which I need to multiply several times to make the file size bigger for some test purpose. The single row in my data is as follows:
( card_description:chararray,
transaction_date:chararray,
merchant_name:chararray,
merchant_city:chararray,
transaction_amount:float
) ;
I want to simply change the transaction_amount and transaction_date for each row several times and then join all the results to make a single big file.
I am stuck in trying to change the transaction_date.
The date value in the file is
27/05/2010 00:00
r1 = FOREACH data GENERATE card_description,ToDate(transaction_date),merchant_name,merchant_city,
ROUND(RANDOM()*5)*transaction_amount;
result =union data,r1;
In order to alter the transaction datei want to use AddDuration function, but in trying to convert chararray to date, I am facing format related issues and unable to understand the solution.
Can someone guide?
After checking out the ways you can invoke ToDate, currently you are invoking ToDate as:
ToDate(milliseconds)
ToDate(iosstring)
And your format is not in milliseconds, nor follows the ISO 8601 format. You should be invoking it like:
ToDate(userstring, format)
Where format is a pattern string that follows these rules.
Therefore, ToDate should be called like:
-- For a 12hr clock
ToDate(transaction_date, "yyyy/MM/dd hh:mm")
-- For a 24hr clock
ToDate(transaction_date, "yyyy/MM/dd HH:mm")
For AddDuration, remember that the second parameter you provide to it must be a string in the ISO 8601 format. Make sure to read the link so you format the string correctly.
Is there any difference between these two queries?
select * from tbl where ts < '9999-12-31-24.00.00.000000';
and
select * from tbl where ts < timestamp('9999-12-31-24.00.00.000000');
When is the timestamp function required?
Is there a difference in performance?
If ts is a string type:
1st one is comparing like for like as strings
2nd one will cause ts to be converted to date/time
If ts is a date/time type,
1st one will convert the constant to the same date time type as the ts column
2nd one is comparing like for like as date/time
If ts is string type, the 2nd one is worst to use because ts will be converted thus invalidating any indexes.
If ts is date/time, there is no difference
Data type precedence applies to most DB engines
At first glance, the first statement will make a string comparison while the second should make date related comparisons.
It depends on your SQL implementation, although assuming the column "ts" is some date/time type, there's practically no difference.
Most SQL implementations have a cast mapping that instructs the engine how to automatically convert data types that fit some pattern, especially if a literally comparison makes no sense. For example, literally comparing a timestamp to a string doesn't make much sense. However, most engines have a mapping that lets it know a string formatted like a date can be automatically converted to a timestamp, in order to be compared to another timestamps.