joda time ISO DateTime formatting - scala

I'm using joda time to format my ISO Date input string, but I'm getting an exception that my ISO Date is malformed:
Invalid format: "2014-06-20T11:41:08+02:00" is malformed at "+02:00"
This is my code:
val formatter: DateTimeFormatter = ISODateTimeFormat.dateTime.withZone(DateTimeZone.getDefault)
val date: DateTime = formatter.parseDateTime("2014-06-20T11:41:08+02:00")
What's wrong here?

The error comment is slightly misleading here, as Joda formatter you derive from ISODateTimeFormat expects the millisecond part of the date/time string to be present, therefore the following will work fine:
val formatter: DateTimeFormatter = ISODateTimeFormat.dateTime().withZone(DateTimeZone.getDefault())
val date: DateTime = formatter.parseDateTime("2014-06-20T11:41:08.0+02:00")

The answer by Radyk is correct.
ISO 8601 Formats Built-In
However, you needn't specify a formatter at all. The DateTime class has a built-in parser for your ISO 8601 compliant format, used automatically by the constructor.
DateTime dateTime = new DateTime( "2014-06-20T11:41:08+02:00", timeZone );
While the second argument is optional, I suggest you assign a DateTimeZone object to be assigned to the DateTime if you know such a time zone. The input string has an offset-from-UTC, but a time zone is more than just an offset. A time zone includes rules for Daylight Saving Time and other anomalies. Use proper time zone names, never 3 or 4 letter codes like EST or IST.
Other Formats
You can apply many other formats:
Built-in ISO 8601 formatters
Built-in localized (short, medium, long, and full formats, Locale-sensitive)
Custom specified by you.
For example, if you want only the date portion without the time-of-day in your String representation, call ISODateTimeFormat.date() to access a built-in formatter.
Example code in Joda-Time 2.8.
String output = ISODateTimeFormat.date().print( dateTime ); // Format: yyyy-MM-dd
Search StackOverflow for hundreds of other Questions and Answers about formatting date-time values.

Related

How convert string date to unix format with moment

i have this date of String type : 14-03-2019 and i need convert this in unix format.
this my code in javascript:
let time = moment(time).unix();
but moment response me with this error:
deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Arguments:
[0] _isAMomentObject: true, _isUTC: false, _useUTC: false, _l: undefined, _i: 14-03-2019, _f: undefined, _strict: undefined, _locale: [object Object]
Error
at Function.createFromInputFallback (/Users/Hernan/Haip/haip/node_modules/moment/moment.js:320:98)
at configFromString (/Users/Hernan/Haip/haip/node_modules/moment/moment.js:2368:15)
at configFromInput (/Users/Hernan/Haip/haip/node_modules/moment/moment.js:2594:13)
at prepareConfig (/Users/Hernan/Haip/haip/node_modules/moment/moment.js:2577:13)
at createFromConfig (/Users/Hernan/Haip/haip/node_modules/moment/moment.js:2544:44)
at createLocalOrUTC (/Users/Hernan/Haip/haip/node_modules/moment/moment.js:2631:16)
at createLocal (/Users/Hernan/Haip/haip/node_modules/moment/moment.js:2635:16)
at hooks (/Users/Hernan/Haip/haip/node_modules/moment/moment.js:12:29)
at createTagChart (/Users/Hernan/Haip/haip/server/components/utils/index.js:36:18)
at Function.getInfluecerSearched (/Users/Hernan/Haip/haip/server/api/campaign-engine/campaign.model.js:439:39)
at process.internalTickCallback (internal/process/next_tick.js:77:7)
and return a NAN
How can convert my string to unix format with moment ?
Since your date format does not follow the ISO_8601 format you need to provide the input date format to the moment constructor. In your case it appears to be 'DD-MM-YYYY' format and not one of the ISO date time formats, specifically just for date it would be YYYY-MM-DD.
So you need to provide the custom input format as the second argument to the moment constructor.
let time = moment(time, 'DD-MM-YYYY').unix(); // should output the correct value
However i suggest you should try to aim to get the source date-time to be in a standard ISO format than an arbitrary custom date format string as much as possible.

Could not find the format for this date: "2018-09-09T09:04:47+00:00"

Getting Error
java.text.ParseException: Unparseable date: "2018-09-09T09:04:47+00:00"
Whatis the date format is this?
There seems to be some confusion, about this date format, so I will explain.
This is an ISO 8601 date-time value with a timezone offset.
References:
The ISO 8601 page in Wikipedia is accurate and pretty comprehensive.
The W3 Consortium have documented in a TR; here.
The Official version may be obtained from ISO; here.
The Z is an ISO standard timezone specifier. It means the same thing as +00.00, and is known in some circles (e.g. the military) as "Zulu time".
An ISO 8601 date/time does not "have to" end with a Z. There are other forms of timezone specification, and indeed a date/time does not need a timezone at all.
You should not need to trim it off the Z. Java's data-time parsers can parse the Z timezone specifier and give it its correct meaning ... if you use the right pattern.
If an ISO date time is "unparseable", that means that you have (explicitly or implicitly) used the wrong format to parse it.
Unfortunately, different countries (locales) have different default date / time formats, and worse still there is no reliable way (in general) to know which is the correct one to use ... if you don't know where it came from.
Fortunately ... ISO 8601 is an international standard. If you see a date / time that conforms to the ISO 8601 syntax, you know what it means.
There are a number of kinds of ISO 8601 date and date/time representation as explained in the W3 Consortium TR. The different kinds can be distinguished without any ambiguity.
If you are parsing using java.text.SimpleDateFormat, then the correct pattern for this variation of ISO 8601 is "yyyy-MM-dd'T'HH:mm:ssX". The pattern that works with java.time.format.DateTimeFormatter is also "yyyy-MM-dd'T'HH:mm:ssX"
The DateTimeFormatter class also defines a number of standard formats as constants. The format for this kind of ISO 8601 date/time is DateTimeFormatter.ISO_OFFSET_DATE_TIME. The other kinds are defined too.
The Date and Calendar classes and associated classes are legacy classes. It is advisable to use the new java.time classes instead in new code.
You should use 'X' for timezone:
String pattern = "yyyy-MM-dd'T'HH:mm:ssX";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
Date date = simpleDateFormat.parse("2018-09-09T09:04:47+00:00");
System.out.println(date);
Use this convert method to String to date which is ISO format. But in generaly ISO format ends with Z , but if not no problem. This method returns Date, and do it what ever u want from this return value.
public static Date toCalendar( String isoDate)
throws ParseException {
String s = isoDate.replace("Z", "+00:00");
try {
s = s.substring(0, 22) + s.substring(23); // to get rid of the ":"
} catch (IndexOutOfBoundsException e) {
throw new ParseException("Invalid length", 0);
}
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(s);
}
In Java8 TimeApi or later version has this usage,try it ;
OffsetDateTime offsetDateTime = OffsetDateTime.parse( "2018-09-09T09:04:47+01:00" );
Instant instant = offsetDateTime.toInstant();
java.util.Date date = java.util.Date.from( instant );
Or use only this pattern yyyy-MM-dd'T'HH:mm:ssX

Compare String time to Local Server Time

Have a string object with a specific format of date.
Need to check if that dateStr is after the current time on local machine.
Having trouble with conversions and LocalDateTime
String dateStr = "Oct 27 2017 02:29:00 GMT+0000";
public static final String DATE_FORMAT = "MMM dd yyyy HH:mm:ss zzzZ";
I know something is fishy in the below code with the usage of LocalDateTime
public static boolean isFutureDate(String dateStr){
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMAT);
LocalDateTime dateTime = LocalDateTime.parse(dateStr, formatter);
return(dateTime.isAfter(LocalDateTime.now()));
}
Trouble is with timezones and date conversions.
Please help find the right way of checking if a dateStr is after the current local date this in Java 8?
Local… types have no time zone
You are using the wrong type for your data.
The Local… types including LocalDateTime purposely have no concept of time zone or offset-from UTC. As such they not represent a moment on the time line, only rough idea of a range of possible moments. Use LocalDateTime only when the time zone is unknown or irrelevant; never use it for an actual moment in history.
Use OffsetDateDate for values with an offset-from-UTC, a number of hours and minutes.
Use ZonedDateTime for values with an assigned time zone. A time zone such as Asia/Kolkata or America/Montreal is a particular region’s history of past, present, and future changes to its offset-from-UTC. Anomalies such as Daylight Saving Time (DST) mean a change to the offset.
If you know all your inputs are in GMT/UTC, use OffsetDateTime. If the inputs may use time zones, parse as ZonedDateTime objects.
This input data format is terrible. If you have any control, use standard ISO 8601 formats instead when exchanging date-time values as text.
All this has been covered many times already on Stack Exchange. Please search more thoroughly before posting. And search Stack Overflow to learn more. I kept my Answer here brief, as this is a duplicate.
When parsing to a LocalDateTime, you're ignoring the offset (+0000), and I'm not sure if that's what you really want.
In this case, the +0000 offset means the date/time is October 27th 2017 at 02:29 AM in UTC. When you parse to a LocalDateTime, you're ignoring the offset (so it represents only "October 27th 2017 at 02:29 AM", not attached to any timezone) and comparing to your local date/time (or the current date/time in the JVM's default timezone).
If you want to make a comparison that also considers the offset, you can parse it to OffsetDateTime and convert to Instant to compare it with the actual UTC instant, regardless of the timezone.
Also, the month name is in English (I'm assuming it's English, but you can change this accordingly), so you must a java.util.Locale in the formatter (if you don't set a locale, it'll use the JVM default, and it's not guaranteed to always be English):
// parse to OffsetDateTime (use the same formatter)
String dateStr = "Oct 27 2017 02:29:00 GMT+0000";
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MMM dd yyyy HH:mm:ss zzzZ", Locale.US);
OffsetDateTime odt = OffsetDateTime.parse(dateStr, fmt);
// compare Instant's
System.out.println(odt.toInstant().isAfter(Instant.now()));
Although it works for you now, keep in mind that the default locale can be changed without notice, even at runtime. If your input has locale-sensitive date (such as month names), it's better to specify it as above.

String can not be converted to a DateTime with ParseExact method

I have a string 7/24/2013 6:05:00 PM and want to convert it to a DateTime object.
I am using
DateTime newDate = DateTime.ParseExact(date,"M/d/yyyy h:mm:ss tt",
System.Globalization.CultureInfo.InvariantCulture);
but the newDate object is being 09.07.2013 06:45:00. I want it as it is seen above the string version.
Do you have any idea why it is not converted the format I wanted or any opinion would be great how I can render it as a datetime object.
Thank you
As your date is already in a common format style you should try parsing using the current UI culture, in your case en-US.
E.g.
DateTime.ParseExact(date,"M/d/yyyy h:mm:ss tt", System.Globalization.CultureInfo.CurrentCulture);
By using the InvariantCulture the parsing is ignoring all cultural clues whilst parsing your string.
For more information: http://msdn.microsoft.com/en-us/library/dd465121.aspx

Convert datetime YYYYMMDD to DDMMYYYY via T-SQL directly

i can get my datetime populated as 2012-07-24 15:31:21
However, its not in the format that i want. This is my current query
SELECT CONVERT(datetime2(0), convert(varchar(20),GETDATE() , 120))
i need the above displayed datetime in the format DD/MM/YYYY HH:MM:SS.
i have searched all over the place. Converting date format in T-SQL is available generally for datatype Varchar. Can someone advise me for datetime formatting via SQL directly?
thanks.
Either that, or you can specify the date/time format directly as the parameter of the ToString method:
string dateTime = DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss");
or second answer is
You can use any culture that supports the dd-mm-yyyy format like the french one.
For example to format the date time now in a format dd-mm-yyyy you can do as follows:
cultureInfo culture = new cultureinfo("fr-FR");
string oFormatedDate = dtNow.ToString("d", culture);