I want the person to let write in the date of his/her birthday, after that I want to compare it with the number of pi.
But I want the program to be flexible. So the date should not just be like
daymonthyear (13091975) but also like day.month.year (13.09.1975) or like day-month-year (13-09-1975)
I already found a idea but it does not work
String sep = "";
String geb = nf_datum.getText();
geb = geb.replaceAll(".", Matcher.quoteReplacement(sep));
i have found this idea with "replaceAll" here: replaceAll "/" with File.separator
I hope somebody can help me??
Using java8 you can get that string and define a DateTimeFormatter, this will give you the flexibility to parse a string into a LocalDate and you dont need to take care how the string "looks like", after that you will get a LocalDate object from which you can get the year, month and day
String geburtstag = "-";
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("[ddMMyyyy]" + "[ddMMyyyy]" + "[dd.MM.yyyy]" + "[dd-MM-yyyy]");
// case1
geburtstag = "23.06.2017";
LocalDate ldt = LocalDate.parse(geburtstag, formatter);
System.out.println("Year: " + ldt.getYear());
System.out.println("Month: " + ldt.getMonthValue());
System.out.println("Day: " + ldt.getDayOfMonth());
// case2
geburtstag = "23062017";
ldt = LocalDate.parse(geburtstag, formatter);
System.out.println("Year: " + ldt.getYear());
System.out.println("Month: " + ldt.getMonthValue());
System.out.println("Day: " + ldt.getDayOfMonth());
// case3
geburtstag = "23-06-2017";
ldt = LocalDate.parse(geburtstag, formatter);
System.out.println("Year: " + ldt.getYear());
System.out.println("Month: " + ldt.getMonthValue());
System.out.println("Day: " + ldt.getDayOfMonth());
Related
i want to get Canada/Eastern offset value from IST input date
e.g if i input 2016-03-10 10:01 then system return correct Offset is -05:00 Canada/Eastern
but when i input 2020-05-28 10:00 then i want Offset is -04:00 Canada/Eastern
thank you in adavance
public class TimeZoneConversation {
private static final String DATE_FORMAT = "yyyy-M-dd HH:mm";
static ZoneId istZoneId = ZoneId.of("Asia/Kolkata");
static ZoneId etZoneId = ZoneId.of("Canada/Eastern");
public static void main(String[] args) {
String dateInString = "2020-02-28 10:00";
LocalDateTime currentDateTime = LocalDateTime.parse(dateInString, DateTimeFormatter.ofPattern(DATE_FORMAT));
ZonedDateTime currentISTime = currentDateTime.atZone(istZoneId); //India Time
ZonedDateTime currentETime = currentISTime.withZoneSameInstant(etZoneId); //EST Time
System.out.println(currentISTime.toLocalDate() + " " + currentISTime.toLocalTime() + " IST");
System.out.println(currentETime.toLocalDate() + " " + currentETime.toLocalTime() + " EST/Canada");
Instant instant = Instant.now(); // Capture current moment in UTC.
ZonedDateTime canadaTime = instant.atZone(etZoneId);
System.out.println("Offset is " + canadaTime.getOffset() + " " + etZoneId);
}
}
//output of above program
2020-02-28 10:00IST
2020-02-27 23:30 EST/Canada
Offset is -05:00 Canada/Eastern
I don't think you should retrieve the offset from the Instant object. The right way should be to retrieve the offset from ZonedDateTime.
Here is a good explanation for Instant, LocalDateTime and ZonedDateTime: What's the difference between Instant and LocalDateTime?
A working solution for your problem:
// ...
LocalDateTime currentDateTime = LocalDateTime.parse(dateInString, DateTimeFormatter.ofPattern(DATE_FORMAT));
ZonedDateTime currentISTime = currentDateTime.atZone(istZoneId); //India Time
ZonedDateTime currentETime = currentISTime.withZoneSameInstant(etZoneId); //EST Time
System.out.println(currentISTime.toLocalDate() + " " + currentISTime.toLocalTime() + " IST");
System.out.println(currentETime.toLocalDate() + " " + currentETime.toLocalTime() + " EST/Canada");
// apply getOffset() on ZonedDateTime, not on Instant
System.out.println("Offset is " + currentETime.getOffset() + " " + etZoneId);
Output for 2016-03-10 10:01 is Offset is -05:00 Canada/Eastern
Output for 2020-05-28 10:00 is Offset is -04:00 Canada/Eastern
I got a huge problem with converting my calendar objects to readable strings.
Actually I use df.format(cal.getTime()) to get a formatted string, this is not working quite well, because the Date object I get from cal.getTime() is not affected by timezones.
Please bite back any comments like "use joda time"...
I´m looking for a solution to convert directly from calendar objects to string.
These are my formatters:
private DateFormat df = new SimpleDateFormat("HH:mm", Locale.GERMANY); // 13:42 Uhr
private DateFormat df2 = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.GERMANY); // 14.04.2012
If you guys give this code a try, you will see that Date objects are not affected by timezones.
// this date is at wintertime
long milli = 1445945400000l; // CET - central european time
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(milli);
System.out.println(" ");
System.out.println("Kalender setTimeInMillis(" + milli + ");");
System.out.println("Daylight Time ? = " + cal.getTimeZone().useDaylightTime());
System.out.println("Date Time = " + cal.getTime());
System.out.println("Kalender Tag = " + cal.get(Calendar.DATE) + " Monat = " + (cal.get(Calendar.MONTH) + 1) + " Jahr = " + cal.get(Calendar.YEAR));
System.out.println("Kalender Uhrzeit = " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND));
cal.setTimeZone(TimeZone.getTimeZone("Europe/Berlin"));
System.out.println(" ");
System.out.println("Kalender setTimeZone(TimeZone.getTimeZone(\"Europe/Berlin\");");
System.out.println("Daylight Time ? = " + cal.getTimeZone().useDaylightTime());
System.out.println("Date Time = " + cal.getTime());
System.out.println("Kalender Tag = " + cal.get(Calendar.DATE) + " Monat = " + (cal.get(Calendar.MONTH) + 1) + " Jahr = " + cal.get(Calendar.YEAR));
System.out.println("Kalender Uhrzeit = " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND));
// this date is at summertime
long milliS = 1445609700000l; // CEST - central european summertime
Calendar calS = Calendar.getInstance();
calS.setTimeInMillis(milliS);
System.out.println(" ");
System.out.println("Kalender setTimeInMillis(" + milliS + ");");
System.out.println("Daylight Time ? = " + calS.getTimeZone().useDaylightTime());
System.out.println("Date Time = " + calS.getTime());
System.out.println("Kalender Tag = " + calS.get(Calendar.DATE) + " Monat = " + (calS.get(Calendar.MONTH) + 1) + " Jahr = " + calS.get(Calendar.YEAR));
System.out.println("Kalender Uhrzeit = " + calS.get(Calendar.HOUR_OF_DAY) + ":" + calS.get(Calendar.MINUTE) + ":" + calS.get(Calendar.SECOND));
calS.setTimeZone(TimeZone.getTimeZone("Europe/Berlin"));
System.out.println(" ");
System.out.println("Kalender setTimeZone(TimeZone.getTimeZone(\"Europe/Berlin\");");
System.out.println("Daylight Time ? = " + calS.getTimeZone().useDaylightTime());
System.out.println("Date Time = " + calS.getTime());
System.out.println("Kalender Tag = " + calS.get(Calendar.DATE) + " Monat = " + (calS.get(Calendar.MONTH) + 1) + " Jahr = " + calS.get(Calendar.YEAR));
System.out.println("Kalender Uhrzeit = " + calS.get(Calendar.HOUR_OF_DAY) + ":" + calS.get(Calendar.MINUTE) + ":" + calS.get(Calendar.SECOND));
OUTPUT
Kalender setTimeInMillis(1445945400000);
Daylight Time ? = false
Date Time** = Tue Oct 27 11:30:00 GMT 2015
Kalender Tag = 27 Monat = 10 Jahr = 2015
Kalender Uhrzeit = 11:30:0
Kalender setTimeZone(TimeZone.getTimeZone("Europe/Berlin");
Daylight Time ? = true
Date Time = Tue Oct 27 11:30:00 GMT 2015
Kalender Tag = 27 Monat = 10 Jahr = 2015
Kalender Uhrzeit = 12:30:0
Kalender setTimeInMillis(1445609700000);
Daylight Time ? = false
Date Time = Fri Oct 23 14:15:00 GMT 2015
Kalender Tag = 23 Monat = 10 Jahr = 2015
Kalender Uhrzeit = 14:15:0
Kalender setTimeZone(TimeZone.getTimeZone("Europe/Berlin");
Daylight Time ? = true
Date Time = Fri Oct 23 14:15:00 GMT 2015
Kalender Tag = 23 Monat = 10 Jahr = 2015
Kalender Uhrzeit = 16:15:0
You need to set the time zone of the formatter, a quick example:
SimpleDateFormat df = new SimpleDateFormat();
Calendar cal1 = Calendar.getInstance(TimeZone.getTimeZone("GMT+4:00"));
df.setTimeZone(cal1.getTimeZone());
System.out.println(df.format(cal1.getTime()));
Calendar cal2 = Calendar.getInstance(TimeZone.getTimeZone("GMT-3:00"));
df.setTimeZone(cal2.getTimeZone());
System.out.println(df.format(cal2.getTime()));
Output:
10/30/15 1:02 PM
10/30/15 6:02 AM
Be aware that java.util.Date objects do not contain any timezone information by themselves - you cannot set the timezone on a Date object. The only thing that a Date object contains is a number of milliseconds since the "epoch" - 1 January 1970, 00:00:00 UTC.
See https://stackoverflow.com/a/2892156/5445351
Date Has Its Own Time Zone
Confusingly, a java.util.Date is assigned an internal time zone using the JVM's current default time zone. You cannot get or set that zone. The java.util.Calendar class was added to Java to handle time zone and other such issues.
Count From Epoch
long milli = 1445945400000l; // CET - central european time
Usually a number like that is a count-from-epoch in UTC (GMT), not any particular time zone. After creating a date-time object from that number you then assign a time zone to be applied.
Tip: Use an uppercase L on an integer literal to avoid looking like a 1 in many fonts.
java.time
These classes are now outmoded by the java.time framework built into Java 8 and later. The new classes are more sensible and easier to use.
Time Zone
A time zone is more than an offset-from-UTC. A time zone is an offset plus a set of past, present, and future rules for handling anomalies such as Daylight Saving Time. Use a proper time zone such as Europe/Berlin. Avoid using or even thinking about the 3-4 letter codes such as CET & CEST; they are neither standardized nor unique.
Example code
First we get an Instant, a moment on the timeline in UTC, from the count-from-epoch.
long milliSecondsFromEpochInUtc = 1445945400000L;
Instant instant = Instant.ofEpochMilli ( milliSecondsFromEpochInUtc );
Then we assign the desired time zone to get a ZonedDateTime.
ZoneId zoneId = ZoneId.of ( "Europe/Berlin" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );
For output, a formatter by default uses the ZonedDateTime object’s assigned time zone.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime ( FormatStyle.MEDIUM ).withLocale ( Locale.GERMANY );
String output1 = zdt.format ( formatter );
Optionally a formatter may apply a different time zone if specified.
String output2 = zdt.format ( formatter.withZone ( ZoneId.of ( "America/Montreal" ) ) );
Dump to console.
System.out.println ( "instant (UTC): " + instant );
System.out.println ( "zdt: " + zdt );
System.out.println ( "Berlin time zone: " + output1 );
System.out.println ( "Montréal time zone: " + output2 );
When run. Note that all of these represent the same moment on the timeline. Their presentation varies but they all mean the same simultaneous moment.
instant (UTC): 2015-10-27T11:30:00Z
zdt: 2015-10-27T12:30+01:00[Europe/Berlin]
Berlin time zone: 27.10.2015 12:30:00
Montréal time zone: 27.10.2015 07:30:00
I have a problem where i'm trying to find the date and time for a specific long value from the "new beginning of the universe", aka jan 1 1970.
I get a "cannot be dereferenced" error when i try to pass my new value to the toString thing.
What i don't get, is that this works for getting a time in millis and displaying it a more readable date/time format, so why not after i do a bunch of math with it?
import java.util.*;
public class Date {
public static void main(String[] args) {
Date mydate1 = new Date(10000);
System.out.println("The date and time of " +
mydate1.elapse + " from the Unix epoch is " + mydate1.getMyTime());
Date mydate2 = new Date(100000);
System.out.println("The date and time of " +
mydate2.elapse + " from the Unix epoch is " + mydate2.getMyTime());
Date mydate3 = new Date(1000000);
System.out.println("The date and time of " +
mydate3.elapse + " from the Unix epoch is " + mydate3.getMyTime());
Date mydate4 = new Date(10000000);
System.out.println("The date and time of " +
mydate4.elapse + " from the Unix epoch is " + mydate4.getMyTime());
Date mydate5 = new Date(100000000);
System.out.println("The date and time of " +
mydate5.elapse + " from the Unix epoch is " + mydate5.getMyTime());
Date mydate6 = new Date(1000000000);
System.out.println("The date and time of " +
mydate6.elapse + " from the Unix epoch is " + mydate6.getMyTime());
/*Date date7 = new Date(10000000000);
System.out.println("The date and time of " +
date7.elapse + " from the Unix epoch is " + date7.getTime());
Date date8 = new Date(100000000000);
System.out.println("The date and time of " +
date8.elapse + " from the Unix epoch is " + date8.getTime());*/
}
long elapse;
Date() {
elapse = 1;
}
Date(long elapseTime) {
elapse = elapseTime;
}
long getMyTime() {
//java.util.Date date = new.java.util.Date();
long currentMillis = System.currentTimeMillis();
long date = currentMillis + elapse - currentMillis;
System.out.println(date.toString());
You can't call toString() on a long (primitive type) -
// System.out.println(date.toString());
System.out.println(date); // <-- this would work.
System.out.println(String.valueOf(date)); // <-- this would be assignable to a
// String, but it prints the
// same value as the first example.
In
long date = currentMillis + elapse - currentMillis;
The variable date is a primitive (long) and not a object. toString is a method all java classes inherit from java.lang.Object and so will be available in all objects (that are instance of classes). long is just a primitive, primitives do not have methods, they do not inherit from Object either.
So all you need is
System.out.println(date);
The issue is in : System.out.println(date.toString())
date is of primitive type long (its not an object of wrapper class Long). Hence the method toString() is not available for 'date'. rather you can simple use :
System.out.println(date);
If you want to print the formatted Date use the following :
Dste d = new Date(date);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
System.out.println(sdf.format(d));
My controller recieves this String "20120115Z" as a #RequestParam, representing a date.
I would like to transform it to this format: yyyy-MM-dd, so I would have a new string like this 2012-01-15.
As you can see, there's no delimiters, only the 'Z' always as the last character.
My approach was pretty obvious:
String data =
strData.substring(0, 4) + "-" +
strData.substring(4, 6) + "-" +
strData.substring(6, 8);
And it works, but as you know these "magic numbers" are something to avoid. I also tried to use a a regular expression like "^[^\s]{4}[^\s]{2}[^\s]{2}Z$", but without success.
Any idea?
UPDATE: Finally I've done it with Joda-Time DateTime class as #Brian Agnew suggested
DateTimeFormatter fmt = DateTimeFormat.forPattern("YYYYMMdd'T'hhmm'Z'");
String strData = "20120115T0600Z";
DateTime dt = fmt.parseDateTime(strData);
printing method:
private static void printDateTime(DateTime dt) {
int year = dt.getYear();
int month = dt.getMonthOfYear();
int day = dt.getDayOfMonth();
int hour = dt.getHourOfDay();
int minute = dt.getMinuteOfHour();
int second = dt.getSecondOfMinute();
int millis = dt.getMillisOfSecond();
String zone = dt.getZone().toString();
log.info("fecha: "
+ day + "/" + month + "/" + year + " " + hour + ":" + minute + ":" + second + ":" + millis
+ " " + zone + "\n");
}
Output
15/1/2012 6:0:0:0 UTC
Thanks everyone
I would perhaps use a Joda-Time DateTimeFormat.
Why ? It'll check the format, including valid values for hours/minutes/seconds, and give you back a suitable DateTime object which you can do what with (including reformat it using a similar approach).
You simply give it the format that you want to parse and it'll do all the rest. You have a date, so treat it as such.
I am reading in a String from a text file which contains a date in the form of yyMMdd I then want to convert it to type date but when I do that it loses its format. here is an exmaple of what I have tried
String strDate = matcher.group(10); // strDate would contain 111107
SimpleDateFormat formatter1 = new SimpleDateFormat("yyMMdd");
Date date = formatter1.parse(strDate); // after parsing it, the format changes to Thu Nov 03 00:00:00 EDT 2011
But if I take date and put it back into a string like so String tDate = formatter1.format(date); the string then contains the date in the format Id like to see 111107.
Is there a way I can do this? maybe if I could some how call the format function to return a date object instead of String, thanks.
Edit
I read a list of dates in from a file and load them into a map I then compare those dates to the current date which is also in the yyMMdd format and then if the date from the map is more then a week earlier than the current date I prompt the user for input and then write the date and other related info to a file, in the yyMMdd format. The reason I use a map is each line of the text file contains some information and a unique name, and I compared the date for that specific line of data so I do a map.get(aName)
here is the code, hope it helps
dbConnect();
stmt = conn.createStatement();
String query = "select * from OBJECT_BAC_EV where instance = 12";//VALUE <> 'Normal'";
rslt = stmt.executeQuery(query);
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd");
String dateNow = formatter.format(currentDate.getTime());
Date curDate = (Date)formatter.parse(dateNow);
currentDate.setTime(curDate);
currentDate.add(Calendar.DAY_OF_MONTH, -7);
dateNow = formatter.format(currentDate.getTime());
curDate = (Date)formatter.parse(dateNow);
Calendar cDate = Calendar.getInstance();
SimpleDateFormat f = new SimpleDateFormat("yyMMdd");
String strDate = f.format(cDate.getTime());
while(rslt.next())
{
System.out.println(rslt.getRow());
String aValue = rslt.getString("VALUE");
String aName = rslt.getString("NAME");
String aObjRef = rslt.getString("ObjRef");
if(aNoteMap.containsKey(aName))
{
String n = aNoteMap.get(aName);
if(aDateMap.get(aName).before(curDate))
{
int answer = JOptionPane.showConfirmDialog(null, "Would you like to use last weeks note? " + n, "Hey", JOptionPane.YES_NO_OPTION);
if( answer == JOptionPane.YES_OPTION)
{
output.write(aName + " " + aObjRef + " " + aValue + " " + aDateMap.get(aName) + " "
+ n + (System.getProperty("line.separator")));
}
else if( answer == JOptionPane.NO_OPTION)
{
String newNote = JOptionPane.showInputDialog("Enter new note");
output.write(aName + " " + aObjRef + " " + aValue + " " + aDateMap.get(aName) + " "
+ newNote + (System.getProperty("line.separator")));
}
}
else
output.write(aName + " " + aObjRef + " " + aValue + " " + aDateMap.get(aName) + " "
+ n + (System.getProperty("line.separator")));
}
else
output.write(aName + " " + aObjRef + " " + aValue + " " + strDate + " "
+ "" + (System.getProperty("line.separator")));
}
System.out.println("its closing output..");
output.close();
}
The Date class has no "internal" format, it only represents date elements. To output it using a specific format, you need to do the way you did: String tDate = formatter1.format(date);
The reason why you think it has the "wrong format" is probably because when you try to output it, it does a toString() by default, which doesn't format it the way you want.
If you give us more details about how you want to use that date (include your code), then we might be able to provide suggestions on how to inject the formatter into it.
Date always stores the complete information including time. If you parse the date with a SimpleDateFormat that does not contain time info, these fields are set to 0 as in your example.
Date does not store any format info itself.
The SimpleDateFormat.format method always returns a String. It represents the 'date' parameter as a String, with the specified format. For example:
SimpleDateFormat sdf = new SimpleDateFormat('yyMMdd');
Date date = sdf.parse("110510");
String sDate = sdf.format(date); //"110510"
SimpleDateFormat sdf2 = new SimpleDateFormat('yyyy.MM.dd');
String sDate2 = sdf2.format(date); //2011.05.10
It's the best thing for formatting a Date Object.
Written using joda-time, it would like this :
String str = "110107";
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendYearOfCentury(2, 2)
.appendMonthOfYear(2)
.appendDayOfWeek(2)
.toFormatter();
DateTime dateFromDB = formatter.parseDateTime(str);//create DateTime instance
System.out.println("Date:" + formatter.print(dateFromDB));//toString in required format
And it has many other benefits, apparently it will replace the existing Java date libs, which have always been rather painful, in upcoming java releases.
One of the benefits is
DateTime now = new DateTime();
Integer compared = now.minusWeeks(1).compareTo(dateFromDB);
And compareTo does the expected
You could try something like:
class MyDate extends java.util.Date {
static final SimpleDateFormat yymmddFormat = new SimpleDateFormat("yyMMdd");
public MyDate (String s) throws ParseException {
super(yymmddFormat.parse(s).getTime());
}
public String toString () {
return yymmddFormat.format(this);
}
}
Use this class everywhere you currently use a Date object. This should make all your dates look as you want them.