JAVA : Get a wrong current time - date

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);
}

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);

Convert TestNG Start and Stop time to Postgres Without Time Zone

I currently have some TestNG custom reporting code that works with the local MySQL database I have been testing against. The resulting database is postgres due to issues with latest MySQL versions in AWS, in trying to convert the format of TestNG millis over I have been encountering issues with the format which I can't seem to get one that works right.
My custom report code was using the following:
report.reporting.put("startDate", testResult.getStartMillis());
report.reporting.put("endDate", testResult.getEndMillis());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
String startDbTime = sdf.format(report.get("startDate"));
String endDbTime = sdf.format(report.get("endDate"));
When I try some of the dateformatters I am receiving indexing errors like: DateTimeParseException: Text could not be parsed at index 4
I've used some various options like offset or instant with no success.
This is a collection of some of the options I have tried.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
String startDbTime = sdf.format(report.get("startDate"));
String endDbTime = sdf.format(report.get("endDate"));
// OffsetDateTime startDbTime = OffsetDateTime.parse(startRawDbTime);
// OffsetDateTime endDbTime = OffsetDateTime.parse(endRawDbTime);
// ZonedDateTime startDbTime = ZonedDateTime.parse(startRawDbTime);
// ZonedDateTime endDbTime = ZonedDateTime.parse(endRawDbTime);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
String startRawDbTime = sdf.format(report.get("startDate"));
String endRawDbTime = sdf.format(report.get("endDate"));
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
LocalDate startParse = LocalDate.parse(startRawDbTime,formatter);
LocalDate endParse = LocalDate.parse(endRawDbTime,formatter);
Long startTimeRaw = Long.parseLong(report.get("startDate").toString());
Instant startInst = Instant.ofEpochMilli(startTimeRaw);
ZonedDateTime zoneStart = ZonedDateTime.ofInstant(startInst, ZoneOffset.UTC);
LocalDate dateStart = formatter.format(zoneStart);
Is there a conversion step I am missing? I thought it would be simple to convert from millis to something that postgres would accept.
Worked out how to do this with PostGres by resetting the DB table to be a date with time zone, then adjusted my Java code to the following:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String startRawDbTime = sdf.format(report.get("startDate"));
String endRawDbTime = sdf.format(report.get("endDate"));
Timestamp timeStart = Timestamp.valueOf(startRawDbTime);
Timestamp timeEnd = Timestamp.valueOf(endRawDbTime);
With the statement insert updated with the right type:
reportInsert.setObject(4,timeStart, Types.TIMESTAMP);
reportInsert.setObject(5,timeEnd, Types.TIMESTAMP);
Everything works as expected now.

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

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());
}

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

How to modify the date?

I cannot get the add function in Blackberry Java.
// Date
private static DateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss");
private static Calendar cal = Calendar.getInstance();
public static final String date = dateFormat.format(cal.getTime())
.toString();
The cal variable don't have add function because I want to reduce 1 day from current date.
The source stated that used cal.add(Calendar.DATE, -1);.
The following solution works when using Java SE. I haven't verified using BlackBerry Java ME yet. But, given that I am only using functions that exist in both the SE version of Calendar and the BlackBerry version of Calendar, hence I have a good feeling about the accuracy of this solution. Append these lines to your code:
long curTime = cal.getTimeInMillis();
curTime -= 1000*60*60*24;
cal.setTimeInMillis(curTime);
System.out.println(dateFormat.format(cal.getTime()).toString());
Try this:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(cal.getTime() - DateTimeUtilities.ONEDAY);
Updated, based on ecb0628's answer and paulkayuk's comment.
Check Calendar, getTimeInMilis(), setTimeInMillis(long millis), and DateTimeUtilities.ONEDAY.