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.
Related
I'm trying to set the scheduled time when creating an assignment using the Google Classroom API. However, I'm confused about which date format is needed. By the error messages, it seems to accept a string which holds a timestamp and a timezone or Z at the end. Among others, I've tried using System.currentTimeMillis() + "Z", as well as googleDate.getValue() + "Z", googleDate.getValue() since Google Date format seems to be the way to go based on this doc but none of them seem to work.
Any ideas perhaps?
Thank you.
String timezone = timestamp + offset + "";
System.currentTimeMillis()
com.google.api.client.util.DateTime googleDate =
new com.google.api.client.util.DateTime(new java.util.Date());
// Date javaDate = new Date(googleDate.getValue());
CourseWork courseWork = new CourseWork()
.setCourseId(course.getId())
.setTitle("title PUBLISHED 2")
.setDescription("desc")
.setScheduledTime(googleDate.getValue() + "Z")
.setMaxPoints(100.0)
.setDueDate(date)
.setDueTime(timeOfDay)
.setWorkType("ASSIGNMENT")
.setState("PUBLISHED")
;
This is what I get when I manually add a timestamp and turn it into a string.
And this using the Google date instead.
And this with the new Java 8 apis
java.time
I recommend that you use java.time, the modern Java date and time API, for your date and time work. The following code gives the same result as the code from your answer.
LocalDate localDate = LocalDate.now().plusDays(7);
String s = localDate.atStartOfDay(ZoneId.systemDefault())
.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
System.out.println(s);
Output in my time zone today:
2021-10-20T00:00:00+02:00
Compared to your own answer you have fewer conversions, and you are freed from writing your own format pattern string since the formatter we need is built in.
This worked:
LocalDate localDate = LocalDate.now().plusDays(7);
java.util.Date date1 = java.util.Date.from(localDate.atStartOfDay()
.atZone(ZoneId.systemDefault())
.toInstant());
String s = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX").format(date1);
It seems the imports were using the Google Date class instead of java.util.date.
i have a really simple problem, i don't know how to deduct the user's date by 01/01 / (the user year) +1. Im really stuck at this point.
public static void main(String[] args)
{
String date;
Scanner teclado = new Scanner (System.in);
System.out.println("Dame una fecha formato dd/mm/yyyy");
date=teclado.next();
Date mydate =FinalAnio.ParseFecha(date);
System.out.println(mydate);
}
public static Date ParseFecha(String fecha)
{
SimpleDateFormat formato = new SimpleDateFormat("dd/mm/yyyy");
Date fechaDate = null;
try
{
fechaDate = formato.parse(fecha);
}
catch (ParseException ex)
{
System.out.println(ex);
}
return fechaDate;
}
The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Do not use mm for the month as it is used for the minute. For the month, the correct symbol is MM. Check DateTimeFormatter to learn more about various symbols used for parsing/formatting string/date-time.
Learn about the calculations of the period and duration from Period and Duration tutorial from Oracle. It would also be worth going through this Wikipedia page on Durations.
Demo:
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Locale;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter date in the format dd/MM/yyyy: ");
String strDate = scanner.next();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/uuuu", Locale.ENGLISH);
LocalDate userDate = LocalDate.parse(strDate, dtf);
// The date representing 01/01/(the user year)+1
LocalDate targetDate = userDate.withDayOfMonth(1).withMonth(1).plusYears(1);
System.out.println("User's date: " + strDate);
System.out.println("Target date: " + targetDate.format(dtf));
Period period = Period.between(userDate, targetDate);
System.out.printf("Difference: %d days %d months %d years%n", period.getDays(), period.getMonths(),
period.getYears());
System.out.println("The difference in terms of days: " + ChronoUnit.DAYS.between(userDate, targetDate));
}
}
A sample run:
Enter date in the format dd/MM/yyyy: 20/10/2015
User's date: 20/10/2015
Target date: 01/01/2016
Difference: 12 days 2 months 0 years
The difference in terms of days: 73
Learn about the modern date-time API from Trail: Date Time.
java.time
I recommend that you use java.time, the modern Java date and time API, for your date work.
DateTimeFormatter formatador = DateTimeFormatter.ofPattern("dd/MM/uuuu");
String entradaUsuario = "02/12/2020";
LocalDate fecha = LocalDate.parse(entradaUsuario, formatador);
LocalDate finDeAƱo = fecha.with(MonthDay.of(Month.DECEMBER, 31));
long diasRestantes = ChronoUnit.DAYS.between(fecha, finDeAƱo);
System.out.println(diasRestantes);
Output is:
29
In the format pattern string upper case MM is for month of year (lower case mm would be minute of hour, so not useful here). uuuu is for year (yyyy would work too).
fecha.with(MonthDay.of(Month.DECEMBER, 31)) adjusts the date to December 31 in the same year.
Link
Oracle tutorial: Date Time explaining how to use java.time.
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.
I have this
DateFormat dateFormat = new SimpleDateFormat("MM");
Date date = new Date();
I know the value as 10 but have got no idea how to print it out. How do I convert it to an int? If there even is a way?
date.getMonth()
it is deprecated - you should be using Calendar, but if you don't want to change, that'll do it. It is 0 indexed, so remember to change the resulting value appropriately.
Javadoc
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);
}