in Java I set the date as time in mSec since 1970, e.g. futuredate=1640995200000l //1 Jan 2022.
When this is compiled into JavaScript by GWT, I believe it uses the Jsdate library which says it is a native javascript date object
1 jan 2022 ends up as this object in the JavaScript _.futuredate={l:3120128, m:391243, h:0}
Can someone help me interpret this format please, it doesn't quite make sense to me
thanks
To work with date and time on the GWT client side one can use com.google.gwt.i18n.shared.DateTimeFormat. com.google.gwt.i18n.shared.DateTimeFormat.PredefinedFormat includes already many predefined formats, but you can naturally use your own, such as "EEEE, y MMMM dd".
Based on your example:
Date myDate = DateTimeFormat.getFormat("dd.MM.yyyy").parse("01.01.2022");
DateTimeFormat myFormat = DateTimeFormat.getFormat(PredefinedFormat.ISO_8601);
String s = myFormat.format(myDate);
The first line only simulates the date that you already set in Java and it is meant to show another example of a date format and how to parse a String.
Related
In Mirth I receive a local datetime string (201801011000) which I need to convert to UTC. I soon found out using the classic js new Date() doesn't work well.
This for example:
var d = new Date("2018-01-01 10:00");
logger.info(d.toString());
gives me an Invalid Date.
So after some more searching I found I can do this:
var d = DateUtil.getDate("yyyyMMddHHmm", "201801011000");
and from here I'm stuck. I don't know how I can convert this to UTC. Local server timezone is assumed which is enough for now, but in the future I also need to set a specific non-local timezone.
I tried to get the methods I can use with Object.getOwnPropertyNames(d), but that gives me the helpfull TypeError: Expected argument of type object, but instead had type object
I also tried looking up the java docs for DateUtil and tried some methods from that, but nothing worked.
Does anybody know how I can convert datestring from local time to UTC? All tips are welcome!
Ok, after messing around with this for about two full days I finally found a solution. In the end I had to tap into Java, but since I couldn't import any java dependencies I had to use their direct class path (e.g.: java.text.SimpleDateFormat).
In the end this is what worked for me:
var datestr = "201207011000".slice(0, 12); // This is just a datetime string to test with
var formatter_hl7 = new java.text.SimpleDateFormat("yyyyMMddHHmm");
formatter_hl7.setTimeZone(java.util.TimeZone.getTimeZone("CET"));
var formatter_utc = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm");
formatter_utc.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
var date_in_utc = formatter_utc.format(formatter_hl7.parse(date_str));
Regardless, I wish you all a beautiful day!
tl;dr
Do not use DateUtil whatever that is. (Perhaps Apache DateUtils library?)
Do not use terrible old date-time classes such as java.util.Date.
Use the modern industry-leading java.time classes.
Code for parsing a string lacking an offset, then assigning an offset of zero for UTC itself.
LocalDateTime // Represents a date and a time-of-day but without any concept of time zone or offset-from-UTC. NOT a moment, NOT a point on the timeline.
.parse(
"201801011000" ,
DateTimeFormatter.ofPattern( "uuuuMMddHHmm" )
)
.atOffset( ZoneOffset.UTC ) // Assign an offset-from-UTC. Do this only if you are CERTAIN this offset was originally intended for this input but was unfortunately omitted from the text. Returns an `OffsetDateTime`.
.toInstant() // Extract an `Instant` from the `OffsetDateTime`. Basically the same thing. But `Instant` is always in UTC by definition, so this type is more appropriate if your intention is to work only in UTC. On the other hand, `Instant` is a basic class, and `OffsetDateTime` is more flexible such as various formatting patterns when generating `String` object to represent its value.
Using java.time
The modern approach in Java uses the java.time classes. This industry-leading framework supplanted the terribly troublesome old date-time classes such as Date, Calendar, and SimpleDateFormat.
DateTimeFormatter
Parse your input string. Define a formatting pattern to match.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuuMMddHHmm" ) ;
String input = "201801011000" ;
LocalDateTime
Parse as a LocalDateTime because your input lacks an indicator for time zone or offset-from-UTC.
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
Lacking a zone or offset means this does not represent a moment, is not a point on the timeline. Instead, this represents potential moments along a range of about 26-27 hours, the range of time zones around the globe.
OffsetDateTime
If you know for certain that this date and time-of-day were intended to represent a moment in UTC, apply the constant ZoneOffset.UTC to get an OffsetDateTime object.
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;
ZonedDateTime
Your Question is vague. It sounds like you might know of an specific time zone intended for this input. If so, assign a ZoneId to get a ZonedDateTime object.
Understand that an offset-from-UTC is but a mere number of hours, minutes, and seconds. Nothing more, nothing less. In contrast, a time zone is much more. A time zone is a history of past, present, and future changes to the offset used by the people of a certain region.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
Instant
A quick way to adjust back into UTC is to extract a Instant object. An Instant is always in UTC.
Instant instan = zdt.toInstant() ;
ISO 8601
Tip: Instead of using custom format for exchanging date-time values as text, use only the standard ISO 8601 formats. The standard formats are practical, easy to parse by machine, easy to read by humans across cultures.
The java.time classes use the ISO 8601 formats by default when parsing/generating strings. The ZonedDateTime::toString method wisely extends the standard to append the name of the zone in square brackets.
Instant instant = Instant.parse( "2018-07-23T16:18:54Z" ) ; // `Z` on the end means UTC, pronounced “Zulu”.
String output = instant.toString() ; // 2018-07-23T16:18:54Z
And always include the offset and time zone in your string. Omitting the offset/zone for a moment is like omitting the currency for a price: All you have left is an ambiguous number worth nothing. Actually, worse than nothing as it can cause all sorts of confusion and errors.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
In my project have function for convert datestring local time to UTC,
function getDateInUTC(dateString) {
return new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm").setTimeZone(java.util.TimeZone.getTimeZone("UTC")).format(new java.text.SimpleDateFormat("yyyyMMddHHmm").setTimeZone(java.util.TimeZone.getTimeZone("CET")).parse(dateString));
}
Enjoy :)
You should use the latest classes java.time provided from Java8.
Steps are as follows:
Step-1. Parse String to LocalDateTime
Step-2. Convert LocalDateTime to the ZonedDateTime and then we can convert between different timezone.
Hope this help:
In Mirth you can write as:
String str = "201207011000";
var date_in_utc =java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
.format(java.time.ZonedDateTime.of(java.time.LocalDateTime
.parse(str,java.time.format.DateTimeFormatter
.ofPattern("yyyyMMddHHmm")),java.time.ZoneId.of("CET"))
.withZoneSameInstant(java.time.ZoneOffset.UTC));
Full Snippet:
ZoneId cet = ZoneId.of("CET");
String str = "201207011000";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
LocalDateTime localtDateAndTime = LocalDateTime.parse(str, formatter);
ZonedDateTime dateAndTimeInCET = ZonedDateTime.of(localtDateAndTime, cet );
System.out.println("Current date and time in a CET timezone : " + dateAndTimeInCET);
ZonedDateTime utcDate = dateAndTimeInCET.withZoneSameInstant(ZoneOffset.UTC);
System.out.println("Current date and time in UTC : " + utcDate);
System.out.println("Current date and time in UTC : " + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").format(utcDate));
Give this a shout
var d = DateUtil.getDate("yyyyMMddHHmm", "201801011000");
var utcD = new Date(d).toISOString();
edit: Info on .toISOString() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
I'm currently working with embarcadero c++, this is the first time I'm working with it so it's completely new to me.
What I'm trying to achieve is to get the current date, make sure the date has the "dd/MM/yyyy" format. When I'm sure this is the case I want to add a month to the current date.
So let's say the current date is 08/18/2016 this has to be changed to 18/08/2016 and then the end result should be 18/09/2016.
I've found that there is a method for this in embarcardero however I'm not sure how to use this.
currently I've only been able to get the current date like this.
TDateTime currentDate = Date();
I hope someone will be able to help me out here.
I figured it out.
After I've searched some more I found the way to use the IncMonth method on this page.
The example given my problem is as follows:
void __fastcall TForm1::edtMonthsExit(TObject *Sender)
{
TDateTime StartDate = edtStartDate->Text;
int Months = edtMonths->Text.ToInt();
TDateTime NextPeriod = IncMonth(StartDate, Months);
edtNextPeriod->Text = NextPeriod;
}
After looking at I changed my code accordingly to this
TDateTime CurrentDate = Date();
TDateTime EndDate = IncMonth(CurrentDate, 1);
A date object doesn't have a format like "dd/MM/yyyy". A date object is internally simply represented as a number (or possibly some other form of representation that really isn't your problem or responsibility).
So you don't have to check if it's in this format because no date objects will ever be in this format, they simply don't have a format.
You will have to do additions/subtractions on the Date object that the language or library gives you, THEN (optionally) you can format it to a human-readable string so it looks like 18/08/2016 or 18th of August 2016 or whatever other readable format that you choose.
It might be that the TRANSFER of a date between 2 systems is in a similar format, but then formatting the date like that is entirely up to you.
As for how to do that, the link you posted seems like a possible way (or alternatively http://docwiki.embarcadero.com/Libraries/Berlin/en/System.SysUtils.IncMonth), I'm afraid I can't give you an example as I'm not familiar with the tool/language involved, I'm just speaking generically about Date manipulations and they should ALWAYS be on the raw object.
I'm trying to convert a string of text into a date with the following code:
//Input String
str = "14/01/26,12:13:13+00"
//Format
format = new java.text.SimpleDateFormat("yy/MM/dd,HH:mm:ssz")
//Conversion
format.parse(str)
But I obtain the following:
Exception: Unparseable date: "14/01/26,12:13:13+00"
How does my format have to be changed in order to parse this date correctly?
+00 is invalid time zone. It should be +0000.
You could add 00 to str and replace z with Z in pattern to use RFC 822 time zone format:
new java.text.SimpleDateFormat("yy/MM/dd,HH:mm:ssZ").parse(str + "00")
// java.util.Date = Sun Jan 26 16:13:13 MSK 2014
java.util.Date (and java.text.SimpleDateFormat) is not the best choice for project. See this answer for some details.
As a bonus DateTimeFormat from Joda-Time allows you to parse your str without modifications:
// I'm using the same pattern with `Z` here
DateTimeFormat.forPattern("yy/MM/dd,HH:mm:ssZ").parseDateTime(str)
// org.joda.time.DateTime = 2014-01-26T16:13:13.000+04:00
If you're looking for "correctness", then don't use SimpleDateFormat!
For one thing, it's not thread safe... and it's silently unsafe, you'll just end up with corrupt dates and no error being thrown. As you're using Scala then it's a fair bet that concurrent programming and thread safety will apply to you.
Use JodaTime, perhaps with one of the Scala wrappers. It gives you some far nicer tools for building date parsers, and generally does the right thing if you simply use the default parser without specifying any format string.
I'm having some problems converting a string to a date object in google apps script.
My dates are in the following format, from a 3rd party API:
2013-01-17T17:34:50.507
I am attempting to convert this to a Date object:
return Date(stringDate);
And this is being returned:
Thu Jan 01 01:00:00 GMT+01:00 1970
Can someone tell me what i'm doing wrong, and how to resolve this issue ?
With moment.js, it is as easy as this to parse any of ISO 8601 format.
var date = Moment.moment("2013-01-17T17:34:50.507").toDate();
You can use moment.js to parse your arbitrary date string as well.
To use moment.js in GAS, you just need to add it in the script editor.
Open your script in GAS script editor and go to "Resources" then "Libraries...", then put this project key MHMchiX6c1bwSqGM1PZiW_PxhMjh3Sh48 and click "Add". Choose the version from the dropdown, then click "Save". Now, you are ready to use moment.js in GAS.
moment.js can be used to parse date string, create formatted date string, and many other date manipulation. Thanks to the author!
You can find the moment.js documentation here.
It doesn't appear that the Date object knows how to handle that date. The date is in ISO 8601 format. Javascript can handle Dates if they are given timezone information.
You will have to do some testing, but if those dates given to you are in UTC time, then just add a Z to the end of the date string before you call new Date().
Edit: The Apps Script Date object can't seem to handle a timezone other than UTC when parsing a Date. I opened an issue for it.
It doesn't work in GScript, at least for me at the time I'm writing it.
This post serves a working alternative: How do I format this date string so that google scripts recognizes it?
As of now new Date() seems to work:
var dT = new Date("2013-01-17T17:34:50.507");
console.info("dT: %s or %d", dT, dT.getTime());
returns dT: Thu Jan 17 17:34:50 GMT+01:00 2013 or 1.358440490507E12 in Google Apps Script
I have a Grails application that needs to parse Dates out of strings that were created with the date.toString() method.
My system's default date.toString() format is "Thu Apr 20 00:27:00 CEST 2006" so I know I can turn a Date into a string and then back into an object using Date.parse('EEE MMM dd HH:mm:ss z yyyy', new Date().toString()).
But that's lame! I shouldn't have to reverse engineer the system's default date format. Plus, I'm not sure under what circumstances the default date format can change, thus breaking that code.
Is there a way to parse a date.toString() back into a Date without using a hand-rolled formatter like that?
Thanks!
Update: I filed this Jira ticket to get such a feature added Groovy. Someone commented on the ticket that Java's date.toString() method is hard-coded to use EEE MMM dd HH:mm:ss z yyyy. That sucks for Java to be so inflexible, but it makes it easier for me to live with hard-coding the formatter!
There's a page over here showing how bad this is in Java (and hence in Groovy)
I agree that there should be a Date.parse method in Groovy which uses this default Date.toString() format.
Maybe it's worth adding a request for improvement over on the Groovy JIRA?
As a temporary workaround, you could add your parse method to the String metaClass in Bootstrap.groovy?
String.metaClass.parseToStringDate = { Date.parse( 'EEE MMM dd HH:mm:ss z yyyy', delegate ) }
Then you can do:
new Date().toString().parseToStringDate()
anywhere in the groovy portions of your grails app
I haven't worked with Grails and I know this is not the answer to your question, but as a workaround, couldn't you just save the format-string as a global variable?
if u use it to convert to json, maybe code below could help:
//bootstrap
JSON.registerObjectMarshaller(Date) {
return it?.format("yyyy-MM-dd HH:mm:ss")
}