How to get local time of different time zones? - java

I want to get local time of different time zones using Java code. Based on the time zone passed to the function I need that time zone's local time. How to achieve this?

java.util.TimeZone tz = java.util.TimeZone.getTimeZone("GMT+1");
java.util.Calendar c = java.util.Calendar.getInstance(tz);
System.out.println(c.get(java.util.Calendar.HOUR_OF_DAY)+":"+c.get(java.util.Calendar.MINUTE)+":"+c.get(java.util.Calendar.SECOND));

I'd encourage you to check out Joda Time, an alternative (but very popular) to the standard Java date and time API:
http://joda-time.sourceforge.net/index.html
Using Joda Time, I think this is what you what:
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
public class TimeZoneDemo {
public static void main(String[] args) {
DateTime now = new DateTime(System.currentTimeMillis(), DateTimeZone.forID("UTC"));
System.out.println("Current time is: " + now);
}
}
You just need to know the standard ID for the time zone in question, such as UTC.

Java 1.8 provides you with some new classes in package java.time:
package learning.java8;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import org.junit.Test;
public class JavaTimeLT {
#Test
public void zonedDataTimeExample() {
final ZoneId zoneId = ZoneId.of("Europe/Zurich");
final ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(Instant.now(), zoneId);
System.out.println(zonedDateTime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
}
}

I wrote the following program to get time for all the Timezones available, see if this helps...
String[] zoneIds = TimeZone.getAvailableIDs();
for (int i = 0; i < zoneIds.length; i++) {
TimeZone tz = TimeZone.getTimeZone(zoneIds[i]);
System.out.print(tz.getID() + " " + tz.getDisplayName());
Calendar calTZ = new GregorianCalendar(tz);
calTZ.setTimeInMillis(new Date().getTime());
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, calTZ.get(Calendar.YEAR));
cal.set(Calendar.MONTH, calTZ.get(Calendar.MONTH));
cal.set(Calendar.DAY_OF_MONTH, calTZ.get(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, calTZ.get(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, calTZ.get(Calendar.MINUTE));
cal.set(Calendar.SECOND, calTZ.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, calTZ.get(Calendar.MILLISECOND));
System.out.println( " "+cal.getTime());

check this. hope it will help.
TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
Calendar cal = Calendar.getInstance();
int LocalOffSethrs = (int) ((cal.getTimeZone().getRawOffset()) *(2.77777778 /10000000));
int ChinaOffSethrs = (int) ((tz.getRawOffset()) *(2.77777778 /10000000));
TimeZone tz1 = TimeZone.getTimeZone("US/Central");
String ss =cal.getTimeZone().getDisplayName();
System.out.println("Local Time Zone : " + ss);
System.out.println("China Time : " + tz.getRawOffset());
System.out.println("Local Offset Time from GMT: " + LocalOffSethrs);
System.out.println("China Offset Time from GMT: " + ChinaOffSethrs);
cal.add(Calendar.MILLISECOND,-(cal.getTimeZone().getRawOffset()));
//cal.add(Calendar.HOUR,- LocalOffSethrs);
cal.add(Calendar.MILLISECOND, tz.getRawOffset());
Date dt = new Date(cal.getTimeInMillis());
System.out.println("After adjusting offset Acctual China Time :" + dt);

In Java 8, you can use the ZonedDateTime.now(ZoneId zone) method:
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));
LocalTime localTime = zonedDateTime.toLocalTime();
System.out.println(localTime);

import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
SimpleDateFormat dateFormat = new SimpleDateFormat();
dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Seoul"));
GregorianCalendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 0);
System.out.println(dateFormat.format( cal.getTime()));

Related

DateTime format in Java

I have the following and I get the time back but I want to add hours to it. I'm not having luck. I have tried SimpleDateTime but cannot seem to get the syntax correct.
package com.sayitfast.service;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class TimeData {
private String time;
private Long milliseconds_since_epoch;
private String date;
#Override
public String toString() {
return "TimeData" + "time=" + time + ", milliseconds_since_epoch="
+ milliseconds_since_epoch + ", date=" + date;
}
public void TimeData() {
}
public void mytimdData() throws IOException {
String webPage = "http://time.jsontest.com";
InputStream is = nw URL(webPage).openStream();
final Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
Gson gson = new Gson();
TimeData td = gson.fromJson(reader, TimeData.class);
System.out.println(td.time);
}
}
You may need to add
String webPage = "http://time.jsontest.com";
InputStream is = new URL(webPage).openStream();
final Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
Gson gson = new Gson();
TimeData td = gson.fromJson(reader, TimeData.class);
System.out.println(td.toString());
System.out.println(td.getTime());
DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
Date date = (Date)formatter.parse(td.getTime());
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, 1);
Date dates = cal.getTime();
System.out.println(dates);
Here I have increased the time to 1hr. This is an example you can change as per your requirement
Also, you can use Date incrementedDate = DateUtils.addHour(date, 1); instead of Calender
I recommend you switch from the outdated and error-prone java.util date-time API to the rich set of modern date-time API and do it as follows (includes demo of some custom formats as well):
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(final String[] args) {
// Custom formats
DateTimeFormatter formatter24Hour = DateTimeFormatter.ofPattern("HH:mm:ss");
DateTimeFormatter formatter12Hour = DateTimeFormatter.ofPattern("hh:mm:ss a");
// Get the number of milliseconds from the epoch of 1970-01-01T00:00:00Z.
long epochMilli = Instant.now().toEpochMilli();
System.out.println("The number of milliseconds from the epoch is " + epochMilli);
System.out.println();
// Get Instant from the number of milliseconds from the epoch
Instant instant = Instant.ofEpochMilli(epochMilli);
// Get LocalDateTime from Instant
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());// Use the zone as per your requirement
LocalDateTime ldt = zdt.toLocalDateTime();
System.out.println("Date-time in your time-zone: " + ldt);
System.out.println("Time in your time-zone: " + ldt.format(DateTimeFormatter.ISO_LOCAL_TIME));
System.out.println("Time in your time-zone: " + ldt.format(formatter24Hour));
System.out.println("Time in your time-zone: " + ldt.format(formatter12Hour));
System.out.println();
// Add some hours e.g. 2 hours to LocalDateTime
LocalDateTime newDateTime = ldt.plus(2, ChronoUnit.HOURS);
System.out.println("Date-time in your time-zone after 2 hours: " + newDateTime);
}
}
Output:
The number of milliseconds from the epoch is 1593532251048
Date-time in your time-zone: 2020-06-30T16:50:51.048
Time in your time-zone: 16:50:51.048
Time in your time-zone: 16:50:51
Time in your time-zone: 04:50:51 pm
Date-time in your time-zone after 2 hours: 2020-06-30T18:50:51.048

How to find current month length in Java?

This is my Java code to find the current month/date we are in:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class GetCurrentDateTime {
private static final DateFormat sdf = new SimpleDateFormat("MM-dd");
public static void main(String[] args) {
Date date = new Date();
System.out.println(sdf.format(date));
}
}
I want this code to do something else. When the code finds the month we are in, I also want it to find the month length. Result should be like this:
08-16
31
Can you help me with this? Thank you.
tl;dr
YearMonth.now()
.lengthOfMonth()
Details
Avoid the troublesome old date-time classes seen in the Question. Now supplanted by the java.time classes.
A time zone is crucial in determining today's date and therefore in determining the current month. For any given moment the date varies around the globe by zone.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
YearMonth ym = YearMonth.now( z ) ;
int daysInMonth = ym.lengthOfMonth() ;
You could try something like this, but I think, there might be a better way:
Date date = new Date();
System.out.println(sdf.format(date));
Calendar c = Calendar.getInstance();
c.setTime(date);
System.out.println(c.getActualMaximum(Calendar.DAY_OF_MONTH));
Output is this:
08-16
31
EDIT:
As written in the Comments:
Use the solution from Basil YearMonth.now().lengthOfMonth(), it's a better way than this
Maybe that:
#Test
public void daysOfMonthTest() throws Exception {
Calendar mycal = new GregorianCalendar();
assertEquals(
31,
mycal.getActualMaximum(Calendar.DAY_OF_MONTH));
}
Note: The Months are numbered from 0 (January) to 11 (December).
Using Simple Date Object:
Date date = new Date();
int month = date.getMonth() + 1;
int year = date.getYear()+1900;
System.out.print(month+"-"+year);
Output:
8-2017
Using Calendar Object:
Date date = new Date(); // your date
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH) + 1;
System.out.print(month+"-"+year);
System.out.print("Number of days: "+cal.getActualMaximum(Calendar.DAY_OF_MONTH));
Output:
8-2017
Number of days: 31
Using JodaTime:
DateTime dateTime = new DateTime();
System.out.print(dateTime.getMonthOfYear()+"-"+(dateTime.getYear()));
System.out.print("Number of days: "+ dateTime.dayOfMonth().getMaximumValue());
Output:
8-2017
Number of days: 31

Separate DateTime to Date and Time with time zone `Z` at the end, in Joda-Time

I have a Joda-Time DateTime object and need to have date and time separately, with time zone label at the end:
DateTime dateTime = new DateTime();
System.out.println(dateTime.toString("YYYY-MM-ddZ"));
System.out.println(dateTime.toString("HH:mm:ssZ"));
In this case the output will be:
2014-02-27+0000
15:10:36+0000
Almost exactly what I need, but it is possible to have it like this?
2014-02-27Z
15:10:36Z
Here's a working example
DateTime dateTime = new DateTime();
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd")
.appendTimeZoneOffset("Z", false, 2, 2)
.toFormatter();
System.out.println(formatter.print(dateTime.withZone(DateTimeZone
.forID("Zulu"))));
Basically, if the time zone offset is zero, you print Z. Since Zulu or UTC has an offset of 0, that's what will be printed.
If you're trying to use Military codes (i.e. Z for GMT see: http://www.timeanddate.com/library/abbreviations/timezones/military/z.html) you could so something like this:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.Date;
public class CalendarExample {
static final String MILITARY_OFFSETS = "YXWVUTSRQPONZABCDEFGHIKLM";
static final int MILLIS_IN_HOUR = 1000*60*60;
public static void main(String[] args) {
System.out.println(formatDate(new Date(), "yyyy-MM-dd", "GMT")); // 2014-02-27Z
System.out.println(formatDate(new Date(), "HH:mm:ss", "GMT"));
System.out.println(formatDate(new Date(), "yyyy-MM-dd", "EST"));
System.out.println(formatDate(new Date(), "HH:mm:ss", "EST"));
}
static String formatDate(Date date, String dateTimeFormat, String timezoneCode) {
Calendar calendar = new GregorianCalendar();
TimeZone tz = TimeZone.getTimeZone(timezoneCode);
calendar.setTimeZone(tz);
int offset = calendar.get(Calendar.ZONE_OFFSET)/MILLIS_IN_HOUR;
// System.out.println(timezoneCode + " Offset is " + offset + " hours");
String timeZoneCode = MILITARY_OFFSETS.substring(offset + 12, offset + 13);
SimpleDateFormat dateFmt = new SimpleDateFormat(dateTimeFormat + "'" + timeZoneCode + "'");
return dateFmt.format(date);
}
}
output:
2014-02-27Z
11:57:44Z
2014-02-27R
11:57:44R
Try this
DateTime dateTime = new DateTime();
System.out.println(dateTime.toString("YYYY-MM-dd z");
System.out.println(dateTime.toString("HH:mm:ss z");
Use "z" instead of "Z".

Get the number of milliseconds since some date

How to get the number of milliseconds from October 15th 2011 1:52:34 P.M.
I can get the number of milliseconds from the current time.
Date date = new Date();
long currentTime = date.getTime();
System.out.println("Current time in long: " + currentTime);
long now = System.currentTimeMillis(); // Simpler way to get current time
Date date = new SimpleDateFormat("dd yyyy h:mm:ss a").parse("15 2011 1:52:34 PM");
long timeElapsed = now - date.getTime(); // Here's your number of ms
Use the Calendar API. Then set the month, date and the time you want (October 15, 2011).
To get you started look into this:
Calendar c = Calendar.getInstance();
Hope this helps!
Link
import java.util.Calendar;
import java.util.Date;
public class TimeMilisecond {
public static void main(String[] argv) {
long lDateTime = new Date().getTime();
System.out.println("Date() - Time in milliseconds: " + lDateTime);
Calendar lCDateTime = Calendar.getInstance();
System.out.println("Calender - Time in milliseconds :" + lCDateTime.getTimeInMillis());
}
}
You could use SimpleDateFormat to parse an arbitrariy date and get the difference in ms.
Use java.util.Calendar and fill it with your date information. Then use java.util.Calendar.getTimeInMillis() to get the number of milliseconds since epoch.

How to get the first day of the current week and month?

I have the date of several events expressed in milliseconds[1], and I want to know which events are inside the current week and the current month, but I can't figure out how to obtain the first day (day/month/year) of the running week and convert it to milliseconds, the same for the first day of the month.
[1]Since January 1, 1970, 00:00:00 GMT
This week in milliseconds:
// get today and clear time of day
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0); // ! clear would not reset the hour of day !
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
// get start of this week in milliseconds
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
System.out.println("Start of this week: " + cal.getTime());
System.out.println("... in milliseconds: " + cal.getTimeInMillis());
// start of the next week
cal.add(Calendar.WEEK_OF_YEAR, 1);
System.out.println("Start of the next week: " + cal.getTime());
System.out.println("... in milliseconds: " + cal.getTimeInMillis());
This month in milliseconds:
// get today and clear time of day
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0); // ! clear would not reset the hour of day !
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
// get start of the month
cal.set(Calendar.DAY_OF_MONTH, 1);
System.out.println("Start of the month: " + cal.getTime());
System.out.println("... in milliseconds: " + cal.getTimeInMillis());
// get start of the next month
cal.add(Calendar.MONTH, 1);
System.out.println("Start of the next month: " + cal.getTime());
System.out.println("... in milliseconds: " + cal.getTimeInMillis());
The first day of week can be determined with help of java.util.Calendar as follows:
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.setTimeInMillis(timestamp);
while (calendar.get(Calendar.DAY_OF_WEEK) > calendar.getFirstDayOfWeek()) {
calendar.add(Calendar.DATE, -1); // Substract 1 day until first day of week.
}
long firstDayOfWeekTimestamp = calendar.getTimeInMillis();
The first day of month can be determined as follows:
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.setTimeInMillis(timestamp);
while (calendar.get(Calendar.DATE) > 1) {
calendar.add(Calendar.DATE, -1); // Substract 1 day until first day of month.
}
long firstDayOfMonthTimestamp = calendar.getTimeInMillis();
Pretty verbose, yes.
Java 7 will come with a much improved Date and Time API (JSR-310). If you can't switch yet, then you can as far use JodaTime which makes it all less complicated:
DateTime dateTime = new DateTime(timestamp);
long firstDayOfWeekTimestamp = dateTime.withDayOfWeek(1).getMillis();
and
DateTime dateTime = new DateTime(timestamp);
long firstDayOfMonthTimestamp = dateTime.withDayOfMonth(1).getMillis();
java.time
The java.time framework in Java 8 and later supplants the old java.util.Date/.Calendar classes. The old classes have proven to be troublesome, confusing, and flawed. Avoid them.
The java.time framework is inspired by the highly-successful Joda-Time library, defined by JSR 310, extended by the ThreeTen-Extra project, and explained in the Tutorial.
Instant
The Instant class represents a moment on the timeline in UTC.
The java.time framework has a resolution of nanoseconds, or 9 digits of a fractional second. Milliseconds is only 3 digits of a fractional second. Because millisecond resolution is common, java.time includes a handy factory method.
long millisecondsSinceEpoch = 1446959825213L;
Instant instant = Instant.ofEpochMilli ( millisecondsSinceEpoch );
millisecondsSinceEpoch: 1446959825213 is instant: 2015-11-08T05:17:05.213Z
ZonedDateTime
To consider current week and current month, we need to apply a particular time zone.
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );
In zoneId: America/Montreal that is: 2015-11-08T00:17:05.213-05:00[America/Montreal]
Half-Open
In date-time work, we commonly use the Half-Open approach to defining a span of time. The beginning is inclusive while the ending in exclusive. Rather than try to determine the last split-second of the end of the week (or month), we get the first moment of the following week (or month). So a week runs from the first moment of Monday and goes up to but not including the first moment of the following Monday.
Let's the first day of the week, and last. The java.time framework includes a tool for that, the with method and the ChronoField enum.
By default, java.time uses the ISO 8601 standard. So Monday is the first day of the week (1) and Sunday is last (7).
ZonedDateTime firstOfWeek = zdt.with ( ChronoField.DAY_OF_WEEK , 1 ); // ISO 8601, Monday is first day of week.
ZonedDateTime firstOfNextWeek = firstOfWeek.plusWeeks ( 1 );
That week runs from: 2015-11-02T00:17:05.213-05:00[America/Montreal] to 2015-11-09T00:17:05.213-05:00[America/Montreal]
Oops! Look at the time-of-day on those values. We want the first moment of the day. The first moment of the day is not always 00:00:00.000 because of Daylight Saving Time (DST) or other anomalies. So we should let java.time make the adjustment on our behalf. To do that, we must go through the LocalDate class.
ZonedDateTime firstOfWeek = zdt.with ( ChronoField.DAY_OF_WEEK , 1 ); // ISO 8601, Monday is first day of week.
firstOfWeek = firstOfWeek.toLocalDate ().atStartOfDay ( zoneId );
ZonedDateTime firstOfNextWeek = firstOfWeek.plusWeeks ( 1 );
That week runs from: 2015-11-02T00:00-05:00[America/Montreal] to 2015-11-09T00:00-05:00[America/Montreal]
And same for the month.
ZonedDateTime firstOfMonth = zdt.with ( ChronoField.DAY_OF_MONTH , 1 );
firstOfMonth = firstOfMonth.toLocalDate ().atStartOfDay ( zoneId );
ZonedDateTime firstOfNextMonth = firstOfMonth.plusMonths ( 1 );
That month runs from: 2015-11-01T00:00-04:00[America/Montreal] to 2015-12-01T00:00-05:00[America/Montreal]
YearMonth
Another way to see if a pair of moments are in the same month is to check for the same YearMonth value.
For example, assuming thisZdt and thatZdt are both ZonedDateTime objects:
boolean inSameMonth = YearMonth.from( thisZdt ).equals( YearMonth.from( thatZdt ) ) ;
Milliseconds
I strongly recommend against doing your date-time work in milliseconds-from-epoch. That is indeed the way date-time classes tend to work internally, but we have the classes for a reason. Handling a count-from-epoch is clumsy as the values are not intelligible by humans so debugging and logging is difficult and error-prone. And, as we've already seen, different resolutions may be in play; old Java classes and Joda-Time library use milliseconds, while databases like Postgres use microseconds, and now java.time uses nanoseconds.
Would you handle text as bits, or do you let classes such as String, StringBuffer, and StringBuilder handle such details?
But if you insist, from a ZonedDateTime get an Instant, and from that get a milliseconds-count-from-epoch. But keep in mind this call can mean loss of data. Any microseconds or nanoseconds that you might have in your ZonedDateTime/Instant will be truncated (lost).
long millis = firstOfWeek.toInstant().toEpochMilli(); // Possible data loss.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
Attention!
while (calendar.get(Calendar.DAY_OF_WEEK) > calendar.getFirstDayOfWeek()) {
calendar.add(Calendar.DATE, -1); // Substract 1 day until first day of week.
}
is good idea, but there is some issue:
For example, i'm from Ukraine and calendar.getFirstDayOfWeek() in my country is 2 (Monday).
And today is 1 (Sunday). In this case calendar.add not called.
So, correct way is change ">" to "!=":
while (calendar.get(Calendar.DAY_OF_WEEK) != calendar.getFirstDayOfWeek()) {...
You can use the java.time package (since Java8 and late) to get start/end of day/week/month.
The util class example below:
import org.junit.Test;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
public class DateUtil {
private static final ZoneId DEFAULT_ZONE_ID = ZoneId.of("UTC");
public static LocalDateTime startOfDay() {
return LocalDateTime.now(DEFAULT_ZONE_ID).with(LocalTime.MIN);
}
public static LocalDateTime endOfDay() {
return LocalDateTime.now(DEFAULT_ZONE_ID).with(LocalTime.MAX);
}
public static boolean belongsToCurrentDay(final LocalDateTime localDateTime) {
return localDateTime.isAfter(startOfDay()) && localDateTime.isBefore(endOfDay());
}
//note that week starts with Monday
public static LocalDateTime startOfWeek() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MIN)
.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
}
//note that week ends with Sunday
public static LocalDateTime endOfWeek() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MAX)
.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
}
public static boolean belongsToCurrentWeek(final LocalDateTime localDateTime) {
return localDateTime.isAfter(startOfWeek()) && localDateTime.isBefore(endOfWeek());
}
public static LocalDateTime startOfMonth() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MIN)
.with(TemporalAdjusters.firstDayOfMonth());
}
public static LocalDateTime endOfMonth() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MAX)
.with(TemporalAdjusters.lastDayOfMonth());
}
public static boolean belongsToCurrentMonth(final LocalDateTime localDateTime) {
return localDateTime.isAfter(startOfMonth()) && localDateTime.isBefore(endOfMonth());
}
public static long toMills(final LocalDateTime localDateTime) {
return localDateTime.atZone(DEFAULT_ZONE_ID).toInstant().toEpochMilli();
}
public static Date toDate(final LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(DEFAULT_ZONE_ID).toInstant());
}
public static String toString(final LocalDateTime localDateTime) {
return localDateTime.format(DateTimeFormatter.ISO_DATE_TIME);
}
#Test
public void test() {
//day
final LocalDateTime now = LocalDateTime.now();
System.out.println("Now: " + toString(now) + ", in mills: " + toMills(now));
System.out.println("Start of day: " + toString(startOfDay()));
System.out.println("End of day: " + toString(endOfDay()));
System.out.println("Does '" + toString(now) + "' belong to the current day? > " + belongsToCurrentDay(now));
final LocalDateTime yesterday = now.minusDays(1);
System.out.println("Does '" + toString(yesterday) + "' belong to the current day? > " + belongsToCurrentDay(yesterday));
final LocalDateTime tomorrow = now.plusDays(1);
System.out.println("Does '" + toString(tomorrow) + "' belong to the current day? > " + belongsToCurrentDay(tomorrow));
//week
System.out.println("Start of week: " + toString(startOfWeek()));
System.out.println("End of week: " + toString(endOfWeek()));
System.out.println("Does '" + toString(now) + "' belong to the current week? > " + belongsToCurrentWeek(now));
final LocalDateTime previousWeek = now.minusWeeks(1);
System.out.println("Does '" + toString(previousWeek) + "' belong to the current week? > " + belongsToCurrentWeek(previousWeek));
final LocalDateTime nextWeek = now.plusWeeks(1);
System.out.println("Does '" + toString(nextWeek) + "' belong to the current week? > " + belongsToCurrentWeek(nextWeek));
//month
System.out.println("Start of month: " + toString(startOfMonth()));
System.out.println("End of month: " + toString(endOfMonth()));
System.out.println("Does '" + toString(now) + "' belong to the current month? > " + belongsToCurrentMonth(now));
final LocalDateTime previousMonth = now.minusMonths(1);
System.out.println("Does '" + toString(previousMonth) + "' belong to the current month? > " + belongsToCurrentMonth(previousMonth));
final LocalDateTime nextMonth = now.plusMonths(1);
System.out.println("Does '" + toString(nextMonth) + "' belong to the current month? > " + belongsToCurrentMonth(nextMonth));
}
}
Test output:
Now: 2020-02-16T22:12:49.957, in mills: 1581891169957
Start of day: 2020-02-16T00:00:00
End of day: 2020-02-16T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current day? > true
Does '2020-02-15T22:12:49.957' belong to the current day? > false
Does '2020-02-17T22:12:49.957' belong to the current day? > false
Start of week: 2020-02-10T00:00:00
End of week: 2020-02-16T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current week? > true
Does '2020-02-09T22:12:49.957' belong to the current week? > false
Does '2020-02-23T22:12:49.957' belong to the current week? > false
Start of month: 2020-02-01T00:00:00
End of month: 2020-02-29T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current month? > true
Does '2020-01-16T22:12:49.957' belong to the current month? > false
Does '2020-03-16T22:12:49.957' belong to the current month? > false
I have created some methods for this:
public static String catchLastDayOfCurrentWeek(String pattern) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
return calendarToString(cal, pattern);
}
public static String catchLastDayOfCurrentWeek(String pattern) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
cal.add(Calendar.WEEK_OF_YEAR, 1);
cal.add(Calendar.MILLISECOND, -1);
return calendarToString(cal, pattern);
}
public static String catchTheFirstDayOfThemonth(Integer month, pattern padrao) {
Calendar cal = GregorianCalendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, 1);
return calendarToString(cal, pattern);
}
public static String catchTheLastDayOfThemonth(Integer month, String pattern) {
Calendar cal = GregorianCalendar.getInstance();
cal.setTime(new Date());
cal.set(cal.get(Calendar.YEAR), month, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
return calendarToString(cal, pattern);
}
public static String calendarToString(Calendar calendar, String pattern) {
if (calendar == null) {
return "";
}
SimpleDateFormat format = new SimpleDateFormat(pattern, LocaleUtils.DEFAULT_LOCALE);
return format.format(calendar.getTime());
}
You can see more here.
To get the first day of the month, simply get a Date and set the current day to day 1 of the month. Clear hour, minute, second and milliseconds if you need it.
private static Date firstDayOfMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DATE, 1);
return calendar.getTime();
}
First day of the week is the same thing, but using Calendar.DAY_OF_WEEK instead
private static Date firstDayOfWeek(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_WEEK, 1);
return calendar.getTime();
}
In this case:
// get today and clear time of day
Calendar cal = Calendar.getInstance();
cal.clear(Calendar.HOUR_OF_DAY); <---- is the current hour not 0 hour
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
So the Calendar.HOUR_OF_DAY returns 8, 9, 12, 15, 18 as the current running hour.
I think will be better change such line by:
c.set(Calendar.HOUR_OF_DAY,0);
this way the day always begin at 0 hour
Get First date of next month:-
SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy");
String selectedDate="MM-dd-yyyy like 07-02-2018";
Date dt = df.parse(selectedDate);`enter code here`
calendar = Calendar.getInstance();
calendar.setTime(dt);
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH) + 1);
String firstDate = df.format(calendar.getTime());
System.out.println("firstDateof next month ==>" + firstDate);
A one-line solution using Java 8 features
In Java
LocalDateTime firstOfWeek = LocalDateTime.now().with(ChronoField.DAY_OF_WEEK, 1).toLocalDate().atStartOfDay(); // 2020-06-08 00:00 MONDAY
LocalDateTime firstOfMonth = LocalDateTime.now().with(ChronoField.DAY_OF_MONTH , 1).toLocalDate().atStartOfDay(); // 2020-06-01 00:00
// Convert to milliseconds:
firstOfWeek.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
In Kotlin
val firstOfWeek = LocalDateTime.now().with(ChronoField.DAY_OF_WEEK, 1).toLocalDate().atStartOfDay() // 2020-06-08 00:00 MONDAY
val firstOfMonth = LocalDateTime.now().with(ChronoField.DAY_OF_MONTH , 1).toLocalDate().atStartOfDay() // 2020-06-01 00:00
// Convert to milliseconds:
firstOfWeek.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
You should be able to convert your number to a Java Calendar, e.g.:
Calendar.getInstance().setTimeInMillis(myDate);
From there, the comparison shouldn't be too hard.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;
/**
This Program will display day for, 1st and last days in a given month and year
#author Manoj Kumar Dunna
Mail Id : manojdunna#gmail.com
*/
public class DayOfWeek {
public static void main(String[] args) {
String strDate = null;
int year = 0, month = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter YYYY/MM: ");
strDate = sc.next();
Calendar cal = new GregorianCalendar();
String [] date = strDate.split("/");
year = Integer.parseInt(date[0]);
month = Integer.parseInt(date[1]);
cal.set(year, month-1, 1);
System.out.println(new SimpleDateFormat("EEEE").format(cal.getTime()));
cal.add(Calendar.MONTH, 1);
cal.add(Calendar.DAY_OF_YEAR, -1);
System.out.println(new SimpleDateFormat("EEEE").format(cal.getTime()));
}
}
Simple Solution:
package com.util.calendarutil;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class CalUtil {
public static void main(String args[]){
DateFormat df = new SimpleDateFormat("dd/mm/yyyy");
Date dt = null;
try {
dt = df.parse("23/01/2016");
} catch (ParseException e) {
System.out.println("Error");
}
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
Date startDate = cal.getTime();
cal.add(Calendar.DATE, 6);
Date endDate = cal.getTime();
System.out.println("Start Date:"+startDate+"End Date:"+endDate);
}
}
i use this trick to get the first day of the current month
note the order is
1 for Sunday
2 for Monday
3 for Tuesday
.... and so on
Calendar cal = new GregorianCalendar();
int startDay = cal.get(Calendar.DAY_OF_YEAR) % 7 + 1;
System.out.println(startDay);
public static void main(String[] args) {
System.out.println(getMonthlyEpochList(1498867199L,12,"Monthly"));
}
public static Map<String,String> getMonthlyEpochList(Long currentEpoch, int noOfTerms, String timeMode) {
Map<String,String> map = new LinkedHashMap<String,String>();
int month = 0;
while(noOfTerms != 0) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, month);
calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
Date monthFirstDay = calendar.getTime();
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date monthLastDay = calendar.getTime();
map.put(getMMYY(monthFirstDay.getTime()), monthFirstDay + ":" +monthLastDay);
month--;
noOfTerms--;
}
return map;
}

Categories

Resources