Joda Time: how to parse time and set default date as today's date - scala

I have to parse dates in formats:
HH:mm
dd MMM
dd MMM yyyy
I've managed to handle the last two of them:
val dateParsers = Array(
DateTimeFormat.forPattern("dd MMM").getParser,
DateTimeFormat.forPattern("dd MMM yyyy").getParser,
ISODateTimeFormat.timeParser().getParser
)
val formatter = new DateTimeFormatterBuilder().append(null, dateParsers).toFormatter.withZoneUTC
DateTime.parse(updatedString, formatter.withDefaultYear(currentYear).withLocale(ruLocale))
Everything is ok with dd MMM and dd MMM yyyy, but when I'm trying parse time like 05:40 I'm getting 01-01-1970 date instead of today's date. What is the simplest method to set default date as today's date in parser?

Joda-Time-Formatter only supports withDefaultYear(), not things like withDefaultDate(). Instead you can do this:
DateTimeFormatter timeParser = DateTimeFormat.forPattern("HH:mm");
LocalTime time = timeParser.parseLocalTime("05:40");
DateTimeZone tz = DateTimeZone.getDefault(); // Or DateTimeZone.UTC or DateTimeZone.forID( "Europe/Paris" )
LocalDate today = LocalDate.now(tz);
DateTime moment = today.toLocalDateTime(time).toDateTime(tz);
System.out.println(moment);
// output in my local timezone: 2014-08-20T05:40:00.000+02:00
Note: I have written the solution in Java, because I am not a scala-guy.

Date and Time are completely different, without subclassing DateTimeFormatter and implementing your special "time at todays' date"-algorithm you wont get very far. Either subclass or maybe inject your current date into the string if it matches some regular expression

I'd use withDate()
private static final DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("HH:mm");
#Test
public void test() {
DateTime dateTime = FORMATTER.parseDateTime("05:40");
DateTime now = new DateTime();
dateTime = dateTime.withDate(now.getYear(), now.getMonthOfYear(), now.getDayOfMonth());
System.out.println(dateTime.toDate());
}

Related

I get a expiry date and time from the api how compare it with the current time?

I'm getting a expiry time when i call the log in api in for format of "Thu, 30 Dec 2021 10:24:34 GMT" i want to get the current time and compare it.
By using DateFormat class in intl package,
you can parse from string date to DateTime.
And by using 'isBefore' or 'isAfter' method, you can compare two DateTime.
import 'package:intl/intl.dart';
void main() {
String strDate = "Thu, 30 Dec 2021 10:24:34 GMT";
DateFormat format = DateFormat("EEE, dd MMM yyyy hh:mm:ss");
DateTime parsedDate = format.parse(strDate);
print('parsedDate: $parsedDate');
DateTime now = DateTime.now();
print('now: $now');
print('parsedDate is before now: ${parsedDate.isBefore(now)}');
print('parsedDate is after now: ${parsedDate.isAfter(now)}');
}
If I understand your question correctly, this can help.
DateTime now = DateTime.now();
DateTime then = DateTime.parse(expirlyDateFromApi.toDate().toString());
var difference = now.difference(expirlyDate);

Unparseable date error format in Spring Boot Mongo DB

MongoCollection<Document> Profile_List = db.getCollection("Profile_List");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD");
Date todaydate = format.parse(new Date().toString());
ArrayList<Document> activeList=profile.find(Filters.regex("lastActive",todayDate.toString())).into(new ArrayList<Document>());
This is the code what we have written. We are getting an “Unparseable date error”. Can someone please help?
This is wrong:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD");
Date todaydate = format.parse(new Date().toString());
The expression new Date().toString() does not return a string that conforms to the format yyyy-MM-DD, so if you try to parse it as if it is formatted that way, you will get an exception.
If you want a Date object that represents the current date and time, simply do this:
Date todaydate = new Date();
No need to convert the Date object to a string and trying to parse it.
If you need a string with the current date in the format yyyy-MM-dd then do this:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String todaydate = format.format(new Date());
Note: You used DD in your date format string but you most likely meant dd. See the API documentation of SimpleDateFormat.
If you are trying to get the current date string in yyyy-MM-dd format. You can do format it like this
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateString = simpleDateFormat.format(new Date());

Vaadin - PopupDateField not accepting multiple input date formats

In my project I have a standard DateField format as "dd MMM yyyy". I used setDateFormat("dd MMM yyyy") to se this format. But now users want to enter "MM/dd/yyyy", "MM-dd-yyyy" and "MM dd yyyy" formats too, with the displayable date MUST still be "dd MMM yyyy".
Right now when I enter "31/01/2016" in the DateField with setDateFormat("dd MMM yyyy") I am getting "date format not recognized" error.
My question is how can I make a datefield accept multiple date format inputs(not using the calendar picker).
Any help is much appreciated. Thanks for reading the post!!!
You can override a method handleUnparsableDateString:
public class MyDateField extends DateField {
#Override
protected Date handleUnparsableDateString(String dateString) throws Converter.ConversionException {
return super.handleUnparsableDateString(dateString);
}
}
That method is called when DateField is not able to parse the input. You can parse the input in the method and return a correct Date instance.

JAVA : Get a wrong current time

i try to get the current time like that :
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
String sendingDateAndTime = dateFormat.format(cal.getTime()).trim();
but i get the GMT time when i want the system time (and not the local time because my software will be executed in several countries so i can use the TimeZone object).
I need to use the date library and the GregorianCalendar library but i get the same wrong result.
Many people have the same problem but all the solution that i saw it's to put hard code like "Europe" or something else in the timezone object.
If someone can help you.
Thankssss
---------------------------- UPDATE ------------------------------------
I tried to use the System.currentTimeMillis() and to give it as parameter to calendar object, but i get the GMT time too
How about this for the GMT time?
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
And this for the local computer time?
Calendar calendar = Calendar.getInstance();
DateFormat will default to the local time zone. The internal format of a Calendar object is the number of milliseconds past midnight, January 1, 1970, GMT.
Edited to add: When I run this code, I get my local time.
public static void main (String[] args) {
Calendar calendar = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss z");
String sendingDateAndTime = dateFormat.format(calendar.getTime());
System.out.println(sendingDateAndTime);
}
When I run this code, I get GMT, although the time zone is still my local time zone.
public static void main (String[] args) {
Calendar calendar = Calendar.getInstance();
TimeZone timeZone = calendar.getTimeZone();
int offsetFromUTC = timeZone.getOffset(calendar.getTimeInMillis());
calendar.add(Calendar.MILLISECOND, -offsetFromUTC);
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss z");
String sendingDateAndTime = dateFormat.format(calendar.getTime());
System.out.println(sendingDateAndTime);
}

DateTime format not formatting correctly

I have a datetime format in XML and I'm trying to unmarshall the values as follows:
2013-03-17T19:12:14Z -> 2013-03-17 19:12 +0100
I have used Joda's DateTime and a DateTimeAdapter class to override the unmarshalling. The datetime format is coming out weird, as follows:
{"iMillis":1363510800000,"iChronology":{"iBase":{"iBase":{"iBase":
{"iMinDaysInFirstWeek":4}},"iParam":{"iZone":{"iTransitions":
[-9223372036854775808,-3852662325000,-1691964000000,-1680472800000,
-1664143200000,-1650146 400000,-1633903200000,-1617487200000,
-1601848800000,- etc etc.
Can anyone help me format this date?
I was unable to figure out the answer so I've tried the following:
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm Z");
DateTime dateTime = new DateTime(v);
long dateTimeMiliSec = dateTime.getMillis();
Date date = new Date(dateTimeMiliSec);
return sd.format(date);
So 2013-03-17T09:00:00Z converts to 2013-03-17 09:00 +0000