I have a calendar in Android and when I'm passing custom date as a default date to my calendar after setting the time to calendar. when I'm clicking the calendar to get default date I'm getting one previous date. for ex - 02/02/2021.
What's wrong I'm doing? how to get date that i passed on calendar?
String dbDate = "03/02/2021"; // (dd/MM/yyyy)
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date dateObj = null;
try{
dateObj = simpleDateFormat.parse(dbDate);
}catch (Exception e){
e.printStackTrace();
}
calendar.clear();
calendar.setTime(dateObj);
long year2021 = calendar.getTimeInMillis();
CalendarConstraints.Builder constraintsBuilder = new CalendarConstraints.Builder();
constraintsBuilder.setStart(year2021);
builder = MaterialDatePicker.Builder.datePicker();
builder.setTitleText("SELECT A DATE");
builder.setSelection(year2021);
builder.setCalendarConstraints(constraintsBuilder.build());
materialDatePicker = builder.build();
The legacy date-time API (java.util date-time types and their formatting type, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.
Solution using the modern API:
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String dbDate = "03/02/2021";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("d/M/u", Locale.ENGLISH);
LocalDate date = LocalDate.parse(dbDate, dtf);
ZonedDateTime zdtUtc = date.atStartOfDay(ZoneId.of("Etc/UTC"));
Instant instant = zdtUtc.toInstant();
long millis = instant.toEpochMilli();
System.out.println(instant);
System.out.println(millis);
}
}
Output:
2021-02-03T00:00:00Z
1612310400000
Now, you can set millis to builder as follows:
builder.setSelection(millis);
For any reason, if you need to convert this object of Instant to an object of java.util.Date, you can do so as follows:
Date utilDate = Date.from(instant);
Learn more about the modern date-time API* from Trail: Date Time.
* 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.
Related
I wan to convert the string d (date in UTC format) to String in UTC format with 'T' and increment 5 mins to time. Below is the code
public static void main (String args[]) throws ParseException
{
String d="2021-08-27 06:25:00.716241+00:00";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSSXXX");
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date actualDate = format.parse(d);
String a=format1.format(actualDate);
System.out.println(a);
}
I get output as 2021-08-27T12:06:56 but I need String 'a' as 2021-08-27T06:25:00 and then add 5 mins to it and make it 2021-08-27T06:30:00
Please help
java.time
The java.util Date-Time API 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*.
Solution using java.time, the modern Date-Time API:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String d = "2021-08-27 06:25:00.716241+00:00";
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d H:m:s.SSSSSSXXX", Locale.ENGLISH);
OffsetDateTime odt = OffsetDateTime.parse(d, dtfInput);
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
String str = odt.format(dtfOutput);
System.out.println(str);
// Add 5 minutes to it
odt = odt.plusMinutes(5);
str = odt.format(dtfOutput);
System.out.println(str);
}
}
Output:
2021-08-27T06:25:00
2021-08-27T06:30:00
ONLINE DEMO
Learn more about the modern Date-Time API* from Trail: Date Time.
* 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.
Sat Dec 01 00:00:00 GMT 2012
I have to convert above date into below format
2012-12-01
How can i?
i have tried with following method but its not working
public Date ConvertDate(Date date){
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String s = df.format(date);
String result = s;
try {
date=df.parse(result);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date;
}
Use this.
java.util.Date date = new Date("Sat Dec 01 00:00:00 GMT 2012");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String format = formatter.format(date);
System.out.println(format);
you will get the output as
2012-12-01
String s;
Format formatter;
Date date = new Date();
// 2012-12-01
formatter = new SimpleDateFormat("yyyy-MM-dd");
s = formatter.format(date);
System.out.println(s);
UPDATE My Answer here is now outdated. The Joda-Time project is now in maintenance mode, advising migration to the java.time classes. See the modern solution in the Answer by Ole V.V..
Joda-Time
The accepted answer by NidhishKrishnan is correct.
For fun, here is the same kind of code in Joda-Time 2.3.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
java.util.Date date = new Date(); // A Date object coming from other code.
// Pass the java.util.Date object to constructor of Joda-Time DateTime object.
DateTimeZone kolkataTimeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeInKolkata = new DateTime( date, kolkataTimeZone );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "yyyy-MM-dd");
System.out.println( "dateTimeInKolkata formatted for date: " + formatter.print( dateTimeInKolkata ) );
System.out.println( "dateTimeInKolkata formatted for ISO 8601: " + dateTimeInKolkata );
When run…
dateTimeInKolkata formatted for date: 2013-12-17
dateTimeInKolkata formatted for ISO 8601: 2013-12-17T14:56:46.658+05:30
Modern answer: Use LocalDate from java.time, the modern Java date and time API, and its toString method:
LocalDate date = LocalDate.of(2012, Month.DECEMBER, 1); // get from somewhere
String formattedDate = date.toString();
System.out.println(formattedDate);
This prints
2012-12-01
A date (whether we’re talking java.util.Date or java.time.LocalDate) doesn’t have a format in it. All it’s got is a toString method that produces some format, and you cannot change the toString method. Fortunately, LocalDate.toString produces exactly the format you asked for.
The Date class is long outdated, and the SimpleDateFormat class that you tried to use, is notoriously troublesome. I recommend you forget about those classes and use java.time instead. The modern API is so much nicer to work with.
Except: it happens that you get a Date from a legacy API that you cannot change or don’t want to change just now. The best thing you can do with it is convert it to java.time.Instant and do any further operations from there:
Date oldfashoinedDate = // get from somewhere
LocalDate date = oldfashoinedDate.toInstant()
.atZone(ZoneId.of("Asia/Beirut"))
.toLocalDate();
Please substitute your desired time zone if it didn’t happen to be Asia/Beirut. Then proceed as above.
Link: Oracle tutorial: Date Time, explaining how to use java.time.
You can't format the Date itself. You can only get the formatted result in String. Use SimpleDateFormat as mentioned by others.
Moreover, most of the getter methods in Date are deprecated.
A date-time object is supposed to store the information about the date, time, timezone etc., not about the formatting. You can format a date-time object into a String with the pattern of your choice using date-time formatting API.
The date-time formatting API for the modern date-time types is in the package, java.time.format e.g. java.time.format.DateTimeFormatter, java.time.format.DateTimeFormatterBuilder etc.
The date-time formatting API for the legacy date-time types is in the package, java.text e.g. java.text.SimpleDateFormat, java.text.DateFormat etc.
Demo using modern API:
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
ZonedDateTime zdt = ZonedDateTime.of(LocalDate.of(2012, Month.DECEMBER, 1).atStartOfDay(),
ZoneId.of("Europe/London"));
// Default format returned by Date#toString
System.out.println(zdt);
// Custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
String formattedDate = dtf.format(zdt);
System.out.println(formattedDate);
}
}
Output:
2012-12-01T00:00Z[Europe/London]
2012-12-01
Learn about the modern date-time API from Trail: Date Time.
Demo using legacy API:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.setTimeInMillis(0);
calendar.set(Calendar.YEAR, 2012);
calendar.set(Calendar.MONTH, 11);
calendar.set(Calendar.DAY_OF_MONTH, 1);
Date date = calendar.getTime();
// Default format returned by Date#toString
System.out.println(date);
// Custom format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
}
}
Output:
Sat Dec 01 00:00:00 GMT 2012
2012-12-01
Some more important points:
The java.util.Date object is not a real date-time object like the modern date-time types; rather, it represents the milliseconds from the Epoch of January 1, 1970. When you print an object of java.util.Date, its toString method returns the date-time calculated from this milliseconds value. Since java.util.Date does not have timezone information, it applies the timezone of your JVM and displays the same. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFomrat and obtain the formatted string from it.
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.
I have a formatted date from sqllite database, to use this in a graph view I need to format it in a long number.
The format is:
2012-07-11 10:55:21
how can I convert it to milliseconds?
You can convert the string into a Date object using this code:-
Date d = DateFormat.parse(String s)
And then convert it into milliseconds by using the inbuilt method
long millisec = d.getTime();
Use date.getTime()
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd, HH:mm:ss");
formatter.setLenient(false);
String oldTime = "2012-07-11 10:55:21";
Date oldDate = formatter.parse(oldTime);
long oldMillis = oldDate.getTime();
try this:
import java.util.*;
public class ConvertDateIntoMilliSecondsExample{
public static void main(String args[]){
//create a Date object
Date date = new Date();
System.out.println("Date is : " + date);
//use getTime() method to retrieve milliseconds
System.out.println("Milliseconds since January 1, 1970, 00:00:00 GMT : "
+ date.getTime());
}
}
java.time
Solution using java.time, the modern date-time API*:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(toMillis("2012-07-11 10:55:21"));
}
public static long toMillis(String strDateTime) {
// Replace the parameter, ZoneId.systemDefault() which returns JVM's default
// timezone, as applicable e.g. to ZoneId.of("America/New_York")
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("u-M-d H:m:s", Locale.ENGLISH)
.withZone(ZoneId.systemDefault());
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, dtf);
Instant instant = zdt.toInstant();
return instant.toEpochMilli();
}
}
Output:
1342000521000
Learn more about the the modern date-time API* from Trail: Date Time.
*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.
I will be giving input date time for a timezone and the timezone for the input date time and we want the relevant DateTime in the expected timezone.
And here is my method.
convertToTimezone("03/08/2010 20:19:00 PM","Asia/Shanghai","US/Central");
The above time is the time in Asia/Shanghai. We would like to know what is the corresponding time in US/Central.
It's working fine but I am getting a 1-hour difference from the actual time.
Can I know where I am going wrong?
Here is the code:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class DateUtil {
private static String format_date = "MM/dd/yyyy HH:mm:ss a";
public static void main(String a[]) {
try {
String sourceTimezone = "Asia/Shanghai";
String destTimezone = "US/Central";
String outputExpectedTimezone = convertToTimezone("03/08/2010 20:19:00 PM", sourceTimezone, destTimezone);
System.out.println("outputExpectedTimezone :" + outputExpectedTimezone);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static String convertToTimezone(String inputDate, String inputDateTimezone, String destinationDateTimezone)
throws Exception {
String outputDate = null;
SimpleDateFormat format = new SimpleDateFormat(format_date);
format.setTimeZone(TimeZone.getTimeZone(inputDateTimezone));
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(inputDateTimezone));
calendar.setTime(format.parse(inputDate));
calendar.add(Calendar.MILLISECOND, -(calendar.getTimeZone().getRawOffset()));
calendar.add(Calendar.MILLISECOND, -calendar.getTimeZone().getDSTSavings());
calendar.add(Calendar.MILLISECOND, TimeZone.getTimeZone(destinationDateTimezone).getRawOffset());
outputDate = format.format(calendar.getTime());
return outputDate;
}
}
You shouldn't be adding anything to the calendar - that represents a specific instant in time. In fact, you don't need a calendar at all.
Instead, have two different formats, one for each time zone:
public static String convertToTimezone(String inputDate,
String inputDateTimezone,
String destinationDateTimezone)
throws Exception
{
SimpleDateFormat parser = new SimpleDateFormat(format_date);
parser.setTimeZone(TimeZone.getTimeZone(inputDateTimezone));
Date date = parser.parse(inputDate);
SimpleDateFormat formatter = new SimpleDateFormat(format_date);
formatter.setTimeZone(TimeZone.getTimeZone(outputDateTimezone));
return formatter.format(date);
}
As an aside, I'd thoroughly recommend using Joda Time instead of the built-in date/time API.
java.time
The java.util Date-Time API 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*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API:
Since your input Date-Time does not have timezone information, parse it into a LocalDateTime
Attach the timezone of the input Date-Time with it to get a ZonedDateTime
Use the ZonedDateTime#withZoneSameInstant to convert this ZonedDateTime to the target ZonedDateTime
Return the formatted target ZonedDateTime.
Demo:
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Tests
System.out.println(convertToTimezone("03/08/2010 20:19:00 PM", "Asia/Shanghai", "US/Central"));
System.out.println(convertToTimezone("03/08/2010 20:19:00 PM", "Asia/Shanghai", "America/Mexico_City"));
}
static String convertToTimezone(String inputDate, String inputDateTimezone, String destinationDateTimezone) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss a", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(inputDate, dtf);
ZonedDateTime zdtInput = ldt.atZone(ZoneId.of(inputDateTimezone));
ZonedDateTime zdtDestination = zdtInput.withZoneSameInstant(ZoneId.of(destinationDateTimezone));
return zdtDestination.format(dtf);
}
}
Output:
03/08/2010 06:19:00 AM
03/08/2010 06:19:00 AM
ONLINE DEMO
Note: Avoid using the deprecated ID, US/Central. Use the standard ID, America/Mexico_City where Mexico City is the largest city in this timezone.
Learn more about the modern Date-Time API from Trail: Date Time.
* 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.
I have time stamp as 29-NOV-11 06.05.41.831000000 AM
Using SimpleDateFormat , i cannot really extract millisecond (.831000000) ....831 is millisecond (and i don't know why those 000000. But thats coming from different source. No control on that.)
The extra digits are nano-second. You can't include these in SimpleDateFormat or the standard libraries. The simplest thing to do in you case is to remove them before parsing the date/time.
java.time
Parse your date-time string into the OffsetDateTime using the timezone offset of UTC and convert the result into an Instant.
You can convert the Instant into milliseconds using Instant#toEpochMilli.
Demo:
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("d-MMM-uu h.m.s.n a")
.toFormatter(Locale.ENGLISH)
.withZone(ZoneOffset.UTC);
OffsetDateTime odt = OffsetDateTime.parse("29-NOV-11 06.05.41.831000000 AM", dtf);
Instant instant = odt.toInstant();
long millis = instant.toEpochMilli();
System.out.println(millis);
}
}
Output:
1322546741831
Learn more about the the modern date-time API* from Trail: Date Time.
* 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.
A working solution... A fairly strict regex for this is quite long-winded as you see.
String input = "29-NOV-11 06.05.41.831000000 AM";
input = input
.replaceFirst(
"(\\d+-\\w+-\\d+\\s\\d+\\.\\d+\\.\\d+\\.\\d{3})\\d{6}(\\s(\\w+))",
"$1$2");
try {
SimpleDateFormat sdf = new SimpleDateFormat(
"dd-MMM-yy HH.mm.ss.SSS aa");
Date date = sdf.parse(input);
System.out.println(sdf.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
You could just use substr if the strings are always fixed width and you consider regex a bit of overkill.
input = input.substring(0, 22) + input.substring(28, 31);
If the timestamp is represented by a string you could use a regular expression to parse out the extra zeroes.