the simplest way to change a time to particular timezone - java

there are two string
String date = "9/13/2012";
String time = "5:48pm";
the time is GMT+0, I wanna change it to GMT+8,what is the simplest way to change a time to particular timezone

Parse it using a SimpleDateFormat set to the UTC time zone
Format the parsed Date value using a SimpleDateFormat set to the time zone you're interested in. (It's likely to be something other than just "UTC+8" - you should find out which TZDB time zone ID you really want.
For example:
SimpleDateFormat inputFormat = new SimpleDateFormat("MM/dd/yyyy h:mma", Locale.US);
inputFormat.setTimeZone(TimeZone.getTimeZone("Etc/UTC");
Date date = inputFormat.parse(date + " " + time);
// Or whatever format you want...
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US);
outputFormat.setTimeZone(targetTimeZone);
String outputText = outputFormat.format(date);
(If you can use Joda Time instead, that'd be great - but I understand that it's pretty big for an Android app.)

The Joda-Time library provides a good set of objects for working with dates/times in multiple time zones. http://joda-time.sourceforge.net/
Something like this for example:
String date = "9/13/2012";
String time = "5:48pm";
String[] dateParts = date.split("/");
Integer month = Integer.parseInt(dateParts[0]);
Integer day = Integer.parseInt(dateParts[1]);
Integer year = Integer.parseInt(dateParts[2]);
String[] timeParts = time.split(":");
Integer hour = Integer.parseInt(timeParts[0]);
Integer minutes = Integer.parseInt(timeParts[1].substring(0,timeParts[1].lastIndexOf("p")));
DateTime dateTime = new DateTime(year, month, day, hour, minutes, DateTimeZone.forID("Etc/GMT"));
dateTime.withZone(DateTimeZone.forID("Etc/GMT+8"));

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:
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String date = "9/13/2012";
String time = "5:48pm";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/u h:ma", Locale.UK);
LocalDateTime ldtSource = LocalDateTime.parse(date + " " + time, dtf);
OffsetDateTime odtSource = ldtSource.atOffset(ZoneOffset.UTC);
OffsetDateTime odtTarget = odtSource.withOffsetSameInstant(ZoneOffset.of("+08:00"));
System.out.println(odtTarget);
// In a custom format
System.out.println(odtTarget.format(dtf));
}
}
Output:
2012-09-14T01:48+08:00
9/14/2012 1:48am
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.

Related

Convert a timestamp to ISO format date string

I have a logic in python that I am converting into Java code.
The logic is I need to read from a timestamp attribute in JSON file and convert it into ISO date format.
Python query:
datetime.datetime.fromtimestamp(jsonMsg["time"]).isoformat(timespec='seconds')
Here is the code I wrote in Java
1627065646.444 is an example of the value I get from JSON script
long timestamp = (long) 1627065646.444 * 1000;
Timestamp time = new Timestamp(timestamp);
Date d = new Date(time.getTime());
DateFormat df = new SimpleDateFormat();
String dateToString = df.format(d);
LocalDateTime datetime = LocalDateTime.parse(dateToString, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
ZoneOffset offset = ZoneOffset.UTC;
String formattedTimeStamp = datetime.atOffset(offset).toString();
When I run the code I get compile error "Text '7/23/21 11:40 AM' could not be parsed at index 0
at java.time.format.DateTimeFormatter.parseResolved0"
This exception occurs at LocalDateTime.parse(dateToString, DateTimeFormatter.ISO_LOCAL_DATE_TIME. Can someone please help me in understanding what I am doing wrong here.
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.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
long timestamp = (long) (1627065646.444 * 1000);
Instant instant = Instant.ofEpochMilli(timestamp);
System.out.println(instant);
ZonedDateTime zdt = instant.atZone(ZoneOffset.UTC);
LocalDateTime ldt = zdt.toLocalDateTime();
System.out.println(ldt);
// A custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/u h:m:s a", Locale.ENGLISH);
String formatted = dtf.format(zdt);
System.out.println(formatted);
}
}
Output:
2021-07-23T18:40:46.444Z
2021-07-23T18:40:46.444
7/23/2021 6:40:46 PM
ONLINE DEMO
The Z in the output is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).
Learn more about the modern Date-Time API* from Trail: Date Time.
Apart from this, what else is wrong with your code?
You have done
long timestamp = (long) 1627065646.444 * 1000;
in which 1627065646.444 will be cast to long resulting in 1627065646 and thus the result of the multiplication will be 1627065646000, not 1627065646444 what you are expecting. You need to cast to long after performing the multiplication.
A valuable comment by Ole V.V.:
I’d use Math.round(1627065646.444 * 1000) to make sure that
floating-point inaccuracy is handled.
* 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.

Convert ZonedDateTime to java.util.Date

How do i convert ZonedDateTime to java.util.Date without changing the timezone.
In my below method when i call Date.from(datetime.toInstant()) it convert it to local time zone in my case SGT.
public static void printDate(ZonedDateTime datetime) {
System.out.println("---> " + datetime.format(DateTimeFormatter.ofPattern(API_TIME_STAMP_PATTERN)));
System.out.println(Date.from(datetime.toInstant()));
System.out.println("\n");
}
Output
---> 2019-03-13_08:46:26.593
Wed Mar 13 16:46:26 SGT 2019
You can add offset millis by yourself. See the example using java.util.Date:
long offsetMillis = ZoneOffset.from(dateTime).getTotalSeconds() * 1000;
long isoMillis = dateTime.toInstant().toEpochMilli();
Date date = new Date(isoMillis + offsetMillis);
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*. However, for any reason, if you want to change java.time.ZonedDateTime to java.util.Date, I recommend you avoid any kind of manual calculations when you already have an inbuilt API to meet the requirement.
All you need to do is to add the offset to the input datetime which you can do by using ZonedDateTime#plusSeconds as shown below:
datetime = datetime.plusSeconds(datetime.getOffset().getTotalSeconds());
Date date = Date.from(datetime.toInstant());
Demo:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
// Test
printDate(ZonedDateTime.now(ZoneId.of("Asia/Singapore")));
}
public static void printDate(ZonedDateTime datetime) {
datetime = datetime.plusSeconds(datetime.getOffset().getTotalSeconds());
Date date = Date.from(datetime.toInstant());
// Showing date-time in Singapore timezone
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Singapore"));
System.out.println(sdf.format(date));
}
}
Output:
2021-10-03T05:11:57
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.
I would do as ETO states on his answer with the exception of using TimeUnit for getting the seconds converted into milliseconds:
long offsetMillis = TimeUnit.SECONDS.toMillis(ZoneOffset.from(dateTime).getTotalSeconds());
long isoMillis = dateTime.toInstant().toEpochMilli();
Date date = new Date(isoMillis + offsetMillis);
or the other option would be:
var localDate = LocalDateTime.now();
final long offSetHours = ChronoUnit.HOURS.between(localDate.atZone(ZoneId.of("YOUR_TIME_ZONE_ID")),
localDate.atZone(ZoneId.of("UTC")));
return Date.from(Instant.parse(dateAsStringISO8601).plus(offSetHours, ChronoUnit.HOURS));
Stick to ZonedDateTime
To preserve the time zone simply preserve your ZonedDateTime. It can be formatted directly to the output your require. Don’t involve the outdated and poorly designed Date class.
private static final String API_TIME_STAMP_PATTERN = "yyyy-MM-dd_HH:mm:ss.SSS";
private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz y", Locale.ROOT);
public static void printDate(ZonedDateTime datetime) {
System.out.println("---> " + datetime.format(DateTimeFormatter.ofPattern(API_TIME_STAMP_PATTERN)));
System.out.println(datetime.format(FORMATTER));
System.out.println("\n");
}
Try it out:
ZonedDateTime zdt = ZonedDateTime.of(
2019, 3, 13, 8, 46, 26, 593_000_000, ZoneId.of("Etc/UTC"));
printDate(zdt);
Output:
---> 2019-03-13_08:46:26.593
Wed Mar 13 08:46:26 UTC 2019
Your conversion is not changing the time zone
A Date falsely pretends to have a time zone. It hasn’t got any. So there is no change of time zone going on. toInstant() discards the time zone because an Instant hasn’t got a time zone either. Date.from() performs the conversion withut any regard to time zone. System.out.println() implicitly calls Date.toString(). The toString() method uses the JVM’s default time zone for rendering the string. It’s pretty confusing alright.

Convert Json date to java date

My json respons contains a CreatedOn Date:
{
"CreatedOn" : "\/Date(1406192939581)\/"
}
I need to convert CreatedOn to a simple date format and count the days of difference from CreatedOn Date to Present Date.
When I debug the below code string CreatedOn showing a null value. How come?
JSONObject store = new JSONObject(response);
if (response.contains("CreatedOn"))
{
String CreatedOn = store.getString("CreatedOn");
}
JSONObject store = new JSONObject(response);
if(store.has("CreatedOn")) {
Timestamp stamp = new Timestamp(store.getLong("CreatedOn"));
Date date = new Date(stamp.getTime());
System.out.println(date);
}
or
JSONObject store = new JSONObject(response);
if(store.has("CreatedOn")) {
Integer datetimestamp = Integer.parseInt(store.getString("CreatedOn").replaceAll("\\D", ""));
Date date = new Date(datetimestamp);
DateFormat formatter = new SimpleDateFormat("HH:mm:ss:SSS");
String dateFormatted = formatter.format(date);
}
consider using JSON methods instead of contains. JSON has "has()" which validate if key exists.
You should also make sure that you try {} catch {} the String first, to make sure its valid JSON.
Update:
Your Value is
/Date(1406192939581)/
which means it must be formatted first.
Get it by parsing the string with
Integer datetimestamp = Integer.parseInt(store.getString("CreatedOn").replaceAll("\\D", ""));
java.time
It’s about time that someone provides the modern answer. When this question was asked in 2014, Java 8 had just come out, and with it java.time, the modern Java date and time API. Today I recommend we all use this and avoid the old classes Timestamp, Date, DateFormat and SimpleDateFormat used in the other answer. The old classes were poorly designed and were replaced for a good reason.
Edit: With Java 8 you can directly parse your string from JSON into an Instant using an advanced formatter, which I consider quite elegant:
DateTimeFormatter jsonDateFormatter = new DateTimeFormatterBuilder()
.appendLiteral("/Date(")
.appendValue(ChronoField.INSTANT_SECONDS)
.appendValue(ChronoField.MILLI_OF_SECOND, 3)
.appendLiteral(")/")
.toFormatter();
String createdOn = "/Date(1406192939581)/";
Instant created = jsonDateFormatter.parse(createdOn, Instant::from);
System.out.println("Created on " + created);
Output from this snippet is:
Created on 2014-07-24T09:08:59.581Z
The formatter knows that the last 3 digits are milliseconds of the second and considers all the preceding digits seconds since the epoch, so this works the way it should. To count the days of difference from CreatedOn Date to Present Date:
ZoneId zone = ZoneId.of("Antarctica/South_Pole");
long days = ChronoUnit.DAYS.between(created.atZone(zone).toLocalDate(), LocalDate.now(zone));
System.out.println("Days of difference: " + days);
Output today (2019-12-20):
Days of difference: 1975
Please substitute your desired time zone if it didn’t happen to be Antarctica/South_Pole.
Original answer:
final Pattern jsonDatePattern = Pattern.compile("/Date\\((\\d+)\\)/");
String createdOn = "/Date(1406192939581)/";
Matcher dateMatcher = jsonDatePattern.matcher(createdOn);
if (dateMatcher.matches()) {
Instant created = Instant.ofEpochMilli(Long.parseLong(dateMatcher.group(1)));
System.out.println("Created on " + created);
} else {
System.err.println("Invalid format: " + createdOn);
}
Output is:
Created on 2014-07-24T09:08:59.581Z
I am using a regular expression not only to extract the number from the string, but also for validation of the string.
The modern Instant class represents a point in time. It’s toString method renders the time in UTC, so this is what you see in the output, denoted by the trailing Z.
Link: Oracle tutorial: Date Time explaining how to use java.time.
java.time
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.
Instant#ofEpochMilli
The key here is to get an object of Instant out of the milliseconds in the JSON string. Once you have Instant, you can convert it to other java.time types e.g. ZonedDateTime or even to the legacy java.util.Date.
A note on the regex, \D+: \D specifies a non-digit while + specifies its one or more occurrence(s).
Demo:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
JSONObject store = new JSONObject("{\n" + "\"CreatedOn\" : \"\\/Date(1406192939581)\\/\"\n" + "}");
if (store.has("CreatedOn")) {
// Replace all non-digits i.e. \D+ with a blank string
Instant instant = Instant.ofEpochMilli(Long.parseLong(store.getString("CreatedOn").replaceAll("\\D+", "")));
System.out.println(instant);
// Now you can convert Instant to other java.time types e.g. ZonedDateTime
// ZoneId.systemDefault() returns the time-zone of the JVM. Replace it with the
// desired time-zone e.g. ZoneId.of("Europe/London")
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
// Print the default format i.e. the value of zdt#toString
System.out.println(zdt);
// A custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMMM dd HH:mm:ss uuuu", Locale.ENGLISH);
String strDateTimeFormatted = zdt.format(dtf);
System.out.println(strDateTimeFormatted);
}
}
}
Output:
2014-07-24T09:08:59.581Z
2014-07-24T10:08:59.581+01:00[Europe/London]
Thu July 24 10:08:59 2014
Learn more about the modern date-time API from Trail: Date Time.
How to get java.util.Date from an Instant:
You should avoid using java.util.Date but for whatsoever purpose, if you want to get java.util.Date, all you have to do is to use Date#from as shown below:
Date date = Date.from(instant);

Custom String from ISO Compliant Date

I am getting a date string as 2014-01-11-T00:00:00Z
I want to convert this date to 20140111 i.e YYYYMMDD it should be a string.
Any standard method/function to achieve above?
java.time
Your date-time string, 2014-01-11-T00:00:00Z is a bit weird as I have never seen such a date-time string where there is a hyphen (-) before T. For this kind of string, the following pattern meets the parsing requirement:
yyyy-M-d-'T'H:m:sXXX
Also, with java.time API, I recommend you replace y with u as explained in this answer. For the output string, you do NOT need to define any pattern as there already exists an inbuilt DateTimeFormatter for this pattern: DateTimeFormatter.BASIC_ISO_DATE.
Demo:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String args[]) {
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d-'T'H:m:sXXX", Locale.ENGLISH);
OffsetDateTime odt = OffsetDateTime.parse("2014-01-11-T00:00:00Z", dtfInput);
System.out.println(odt);
String output = odt.toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE);
System.out.println(output);
}
}
Output:
2014-01-11T00:00Z
20140111
Note:
Had your date-time string been ISO 8601 compliant, you would NOT have needed to use a DateTimeFormatter object explicitly for parsing i.e. you could have simply parsed it as
OffsetDateTime odt = OffsetDateTime.parse("2014-01-11T00:00:00Z");
The Z in the date-time stands for Zulu which specifies UTC time (that has a timezone offset of +00:00 hours) in ISO 8601 standard. Thus, this solution will also work for a date-time string like 2014-01-11-T00:00:00+02:00 which has a timezone offset of +02:00 hours.
In case, you need a java.util.Date object from this object of OffsetDateTime, you can do so as follows:
Date date = Date.from(odt.toInstant());
Learn more about the the modern date-time API* from Trail: Date Time.
Note that the legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) are outdated and error-prone. It is recommended to stop using them completely and switch to java.time API. Just for the sake of completeness, I am providing you with a solution using the legacy API.
Using the legacy API:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Main {
public static void main(String args[]) throws ParseException {
SimpleDateFormat sdfInput = new SimpleDateFormat("yyyy-M-d-'T'H:m:sXXX", Locale.ENGLISH);
SimpleDateFormat sdfOutput = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
sdfOutput.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));// Change it as required
Date date = sdfInput.parse("2014-01-11-T00:00:00Z");
String output = sdfOutput.format(date);
System.out.println(output);
}
}
Output:
20140111
* 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.
Take this
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormat {
public static void main(String[] args) throws ParseException {
SimpleDateFormat inFormat = new SimpleDateFormat("yyyy-MM-dd-'T'HH:mm:ss'Z'");
Date inDate = inFormat.parse("2014-01-11-T00:00:00Z");
SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMdd");
String output = outFormat.format(inDate);
System.out.println("Date: " + output);
}
}
Take a look at this thread for Date formatting in Java using Zoulou notation :
Converting ISO 8601-compliant String to java.util.Date
Then create a new SimpleDateFormat using the "yyyyMMdd" format string.
Here an improved version of given answer by #drkunibar:
SimpleDateFormat inFormat = new SimpleDateFormat("yyyy-MM-dd-'T'HH:mm:ss'Z'");
inFormat.setTimeZone(TimeZone.getTimeZone("GMT")); // Z denotes UTC in ISO-8601
Date inDate = inFormat.parse("2014-01-11-T00:00:00Z");
SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMdd");
outFormat.setTimeZone(TimeZone.getTimeZone("...")); // set your timezone explicitly!
String output = outFormat.format(inDate);
System.out.println("Date: " + output);
Note that the format YYYYMMDD is also ISO-8601-compliant (a so-called basic calendar date). The question you have to ask yourself is in which timezone you want to get your output. If in UTC you have to set "GMT", too. Without setting timezone it can happen that your output date differs from input UTC date by one day dependent where your default system timezone is (for example US is several hours behind UTC, in this case one calendar day before UTC midnight).
Update: This Answer is now obsolete. See the modern solution using java.time in the Answer by Avinash.
Joda-Time
This date-time work is much easier with the Joda-Time 2.3 library.
String input = "2014-01-11T00:00:00Z"; // In standard ISO 8601 format.
DateTime dateTime = new DateTime( input, DateTimeZone.UTC ); // Parse string into date-time object.
DateTimeFormatter formatter = ISODateTimeFormat.basicDate(); // Factory to make a formatter.
String output = formatter.print( dateTime ); // Generate string from date-Time object.

Split date/time strings

I have a ReST service which downloads information about events in a persons calendar...
When it returns the date and time, it returns them as a string
e.g. date = "12/8/2012" & time = "11:25 am"
To put this into the android calendar, I need to do the following:
Calendar beginTime = Calendar.getInstance();
beginTime.set(year, month, day, hour, min);
startMillis = beginTime.getTimeInMillis();
intent.put(Events.DTSTART, startMillis);
How can I split the date and time variables so that they are useable in the "beginTime.set() " method?
I don't thinks you really need how to split the string, in your case it should be 'how to get time in milliseconds from date string', here is an example:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateTest {
public static void main(String[] args) {
String date = "12/8/2012";
String time = "11:25 am";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
try {
Date dt = df.parse(date + " " + time);
Calendar ca = Calendar.getInstance();
ca.setTime(dt);
System.out.println(ca.getTimeInMillis());
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Try this:
String date = "12/8/2012";
String time = "11:25 am";
String[] date1 = date.split("/");
String[] time1 = time.split(":");
String[] time2 = time1[1].split(" "); // to remove am/pm
Calendar beginTime = Calendar.getInstance();
beginTime.set(Integer.parseInt(date1[2]), Integer.parseInt(date1[1]), Integer.parseInt(date1[0]), Integer.parseInt(time1[0]), Integer.parseInt(time2[0]));
startMillis = beginTime.getTimeInMillis();
intent.put(Events.DTSTART, startMillis);
Hope this helps.
Assuming you get your date in String format (if not, convert it!) and then this:
String date = "12/8/2012";
String[] dateParts = date.split("/");
String day = dateParts[0];
String month = dateParts[1];
Similarly u can split time as well!
You can see an example of split method here : How to split a string in Java
Then simply use the array for your parameter eg: array[0] for year and etc..
Use SimpleDateFormat (check api docs). If you provide proper time pattern it will be able to convert string into Date instantly.
This is just a Idea, you can do some thing like this without splitting
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm a");
Date date = formatter.parse("12/8/2012 11:25 am");
Calendar cal=Calendar.getInstance();
cal.setTime(date);
java.time either through desugaring or through ThreeTenABP
Consider using java.time, the modern Java date and time API, for your date and time work. With java.time it’s straightforward to parse your two strings for date and time individually and then combine date and time into one object using LoalDate.atTime().
The way I read your code you are really after a count of milliseconds since the epoch. So this is what I am giving you in the first snippet. Feel free to take it apart and use only the lines you need.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d/M/u");
DateTimeFormatter timeFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("h:mm a")
.toFormatter(Locale.ENGLISH);
String dateString = "12/8/2012";
String timeString = "11:25 am";
LocalDate date = LocalDate.parse(dateString, dateFormatter);
LocalTime time = LocalTime.parse(timeString, timeFormatter);
long startMillis = date
.atTime(time)
.atZone(ZoneId.systemDefault())
.toInstant()
.toEpochMilli();
System.out.println(startMillis);
When running in my time zone (at UTC offset +02:00 in August) the output is:
1344763500000
For anyone reading along that does need the individual numbers from the two strings, getting those is straightforward too. For example:
int year = date.getYear();
Month month = date.getMonth();
int monthNumber = date.getMonthValue();
int dayOfMonth = date.getDayOfMonth();
int hourOfDay = time.getHour();
int hourWithinAmOrPm = time.get(ChronoField.HOUR_OF_AMPM);
int minute = time.getMinute();
System.out.format("Year %d month %s or %d day %d hour %d or %d AM/PM minute %d%n",
year, month, monthNumber, dayOfMonth, hourOfDay, hourWithinAmOrPm, minute);
Year 2012 month AUGUST or 8 day 12 hour 11 or 11 AM/PM minute 25
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
Java 8+ APIs available through desugaring
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Categories

Resources