Date and Calender (input string) conversion and manipulation in Java - java

The problem I'm trying to solve is as follows. In Nepal we use Bikram Sambat (BS) as our Calendar and also use Georgian Calendar (AD). What I'm trying to do is convert a BS to AD and an AD to BS. BS is 56 years and 8 months ahead of AD. For example today: 17th Feb 2013 is 4 (day) 11 (month) 2070 (year) in BS.
package Day10;
import java.util.Date;
/**
* This is my driver class
*/
public class Driver {
public static void main (String[] args){
DateUtils dateUtils = new DateUtils(); //Object creation
Date date=dateUtils.getCurrentDate(); //current date
dateUtils.getAd("10 21 2070"); //method invoke for BS to AD. (It is mm/dd/yyyy BS)
}
}
package Day10;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* This is my Service class for converting date values.
*/
final public class DateUtils {
public Date getCurrentDate(){
SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd yyyy");//date format
Date date = new Date();//current date
System.out.println(dateFormat.format(date));
return date;
}
//method to convert BS to AD
public Calendar getAd (String bs){
DateFormat dateFormat = new SimpleDateFormat("MM dd yyyy");//date format
Calendar ad = Calendar.getInstance();
//Converting String Value to Calendar Object
try { ad.setTime(dateFormat.parse(bs));
} catch (ParseException e){
System.out.println("Invalid");
}
System.out.println("Your AD date:"+dateFormat.format(bs));
return ad;
}
}
Problem: While trying to change the String format to Calendar could not determine the variable to store the new converted Calendar value.
I'm trying to change the String value to Calendar and subtract 56 years and 8 months from that. Is that a good possible way?
Thanks.

If you just want to add several years/months to a Calendar, you can
do this as follows. But again, this is not real AD to BS conversion.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Test040 {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Calendar c = new GregorianCalendar();
c.add(Calendar.YEAR, 56);
c.add(Calendar.MONTH, 8);
c.getTime();
System.out.println(sdf.format(c.getTime()));
}
}

When you are parsing a BS String using SimpleDateFormat, it may give parse exception as BS months don't have a same number of dates as AD. Some times a BS month can have 32 days, as anexample, 32-02-2070 is not a valid string. As long as the calculation of number of days in a BS month is implemented in program, I don't think it is possible without any error.

Related

How can I retrieve datetiime from mongodb? By comparing the data with jDateChosser Java

private void showdataTable_btnActionPerformed(java.awt.event.ActionEvent evt) {
try {
DateFormat df = new SimpleDateFormat("YYYY-mm-dd'T'HH:MM:ss'Z'"); //set date format
String set = df.format(dateChoos1.getDate()); //add value to set
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("datetimes", set); //where date via set(date)
DBCursor cursor = table.find(whereQuery);
while (cursor.hasNext()) {
DBObject obj = cursor.next();
String ip_address = (String) obj.get("ip_address");
String mac_address = (String) obj.get("mac_address");
Date datetimes = (Date) obj.get("datetimes");
String url = (String) obj.get("url");
model.insertRow(model.getRowCount(), new Object[]{datetimes, ip_address, mac_address, url});
}
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
Your format, YYYY-mm-dd'T'HH:MM:ss'Z' is not correct. Let's discuss everything which is wrong with this format.
You have used Y instead of y: The symbol Y is used for Week year while y is used for Year. Check Difference between year-of-era and week-based-year? to learn more about it.
You have used mm for month: The correct symbol for the month is M.
You have used MM for minutes: The correct symbol for the minute is m.
You have enclosed Z within single quotes: The symbol, Z is used for Time zone whereas 'Z' is nothing but a character literal. Probably you want to format the timezone offset of +00:00 as Z and for this, you should in fact use X.
So, the correct format is as follows:
yyyy-MM-dd'T'HH:mm:ssX
A demo with the suggested format:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX", Locale.ENGLISH);
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
System.out.println(sdf.format(date));
}
}
Output:
2021-01-14T08:13:01Z
Note that 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.
Use Date#toInstant to convert a java.util.Date object (the legacy type) to java.time.Instant (the modern type). Instant represents an instantaneous point on the time-line and should be just enough for most of your JSON operations. The Instant#toString returns the date-time string with UTC timezone offset which is compliant with ISO-8601 standards.
Demo:
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
Instant instant = date.toInstant();
// Print the value of instant#toString
System.out.println(instant);
OffsetDateTime odt = instant.atOffset(ZoneOffset.UTC);
System.out.println(odt);
// Custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssX", Locale.ENGLISH);
System.out.println(dtf.format(odt));
}
}
Output:
2021-01-14T08:28:35.659Z
2021-01-14T08:28:35.659Z
2021-01-14T08:28:35Z

Get formatted string from Calendar

I've got a Calendar Date in Java.
I need to convert it in a String with this format :
2020-12-29T00:00:00+01:00
How can I do it?
Thank you so much for your help.
Get the Date object by calling Calendar#getTime and format it using a SimpleDateFormat with the format, yyyy-MM-dd'T'HH:mm:ssXXX.
Note: Since the desired string has timezone offset of +01:00 hours, make sure you set the timezone of the SimpleDateFormat object to TimeZone.getTimeZone("GMT+1") before calling SimpleDateFormat#format.
Demo:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) throws ParseException {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+1"));
Date date = calendar.getTime();
String formatted = sdf.format(date);
System.out.println(formatted);
}
}
Another example:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) throws ParseException {
String dateTimeString = "2020-12-29T00:00:00+01:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
Date obj = sdf.parse(dateTimeString);
Calendar calendar = Calendar.getInstance();
calendar.setTime(obj);
// Formatting this calendar object
Date date = calendar.getTime();
sdf.setTimeZone(TimeZone.getTimeZone("GMT+1"));
String formatted = sdf.format(date);
System.out.println(formatted);
}
}
Output:
2020-12-29T00:00:00+01:00
java.time
I recommend that you use java.time, the modern Java date and time API, for your date and time work.
Here’s a formatter for your desired format:
private static final DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXXX");
With this we may do:
ZoneId zone = ZoneId.of("Asia/Barnaul");
ZonedDateTime dateTime
= LocalDate.of(2020, Month.DECEMBER, 29).atStartOfDay(zone);
String formatted = dateTime.format(formatter);
System.out.println(formatted);
Output from this example snipoet is:
2020-12-29T00:00:00+07:00
If you cannot avoid getting a Calendar
If you are getting a Calendar object from a legacy API that you cannot afford to upgrade to java.time just now, convert it to ZonedDateTime. It is almost certainly really a GregorianCalendar (or formatting into that format would not make much sense), which makes the conversion straightforward.
Calendar yourCalendar = getCalendarFromLegacyApi();
ZonedDateTime dateTime
= ((GregorianCalendar) yourCalendar).toZonedDateTime();
The rest is as before, as is the output.
If you need to take into account the possibility that the Calendar is not a GregorianCalendar, use this slightly more complicated conversion instead:
ZonedDateTime dateTime = yourCalendar.toInstant()
.atZone(yourCalendar.getTimeZone().toZoneId());
Link
Oracle tutorial: Date Time explaining how to use java.time.

What should be the format in SimpleDateFormat to print date like this - 01-JUN-20 08.55.27.577984000 AM UTC? [duplicate]

This question already has answers here:
How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?
(16 answers)
How to get the current date/time in Java [duplicate]
(28 answers)
How to format a ZonedDateTime to a String?
(3 answers)
Closed 2 years ago.
I want to print the current date in this format -
01-JUN-20 08.55.27.577984000 AM UTC. Tried lot of formats in SimpleDateformat but none is working. What is the right way to print like this?
SimpleDateFormat
You can use the following pattern:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class TimeFormatting {
public static void main(String[] args) {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy hh.mm.ss.SSS a Z");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String formatted = formatter.format(new Date(2015, 4, 4, 13, 7, 19)); //One example date
System.out.println(formatted);
}
}
This will give the output 04-05-15 11.07.19.000 AM +0000 where +0000 equals to UTC.
Explanation of the pattern dd-MM-yy hh.mm.ss.SSS a Z:
dd = the day
MM = the month
yy = the year
hh = the hour
mm = the minute
ss = the second
SSS = the millisecond. There does not exist a reference to nanoseconds in SimpleDateFormat (see this answer).
a = to show AM/PM
Z = to show the timezone
Additional information
Please note: SimpleDateFormat is deprecated. You should use DateTimeFormatter. One big advantage is that you can also have the nanoseconds (n).
One example:
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.ZoneOffset;
public class TimeFormatting {
public static void main(String[] args) {
ZonedDateTime time = ZonedDateTime.now(ZoneOffset.UTC);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yy hh.mm.ss.n a 'UTC'").withZone(ZoneOffset.UTC);
String timeDate = time.format(formatter);
System.out.println(timeDate);
}
}
Edit:
If you want to have UTC instead of +0000 with SimpleDateFormat you can use dd-MM-yy hh.mm.ss.SSS a zzz instead.

add or sub in Date using calender [duplicate]

This question already has answers here:
Printing out datetime in a specific format in Java?
(4 answers)
Closed 3 years ago.
I want to remove the time from dateAndTime, and also want to have all of them in numeric form like this: 10-10-2019
output: Wed Nov 10 16:39:58 AST 2010
public static void main(String args[]){
//Java calendar in default timezone and default locale
int day =10;
int month =10;
int year =10;
Calendar m = Calendar.getInstance();
m.set(year, month, day);
m.add(day, 10);
System.out.println(" Date :" + m.getTime());
Use SimpleDateFormat. There's a lot of example you can use.
you can use SimpleDateFormat for early versions of java or DateTimeFormatter for java8+.
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
public class DateTests {
public static void main(String[] args) {
//java8+
//recommended
String formattedToday = DateTimeFormatter.ofPattern("MM-dd-YYYY").format(LocalDateTime.now());
System.out.println(formattedToday);
//early versions of java
Calendar today = Calendar.getInstance();
String formatted = new SimpleDateFormat("MM-dd-YYYY").format(today.getTime());
System.out.println(formatted);
}
}
output:
09-18-2019
09-18-2019
Also read Calendar date to yyyy-MM-dd format in java

How to typecast Bigint into Timestamp in java?

Below code I tried by not working out..
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.sql.Timestamp;
public class TimestampTest {
public static void main(String[] args){
long unixSeconds = 1429582984839L; // suffix L
java.util.Date date= new java.util.Date(unixSeconds*1000L);
System.out.println(new Timestamp(date.getTime()));
}}
Expected output:21/04/2015 03:15 AM in this format.....but I am getting 47271-09-06 09:40:39.0
long unixSeconds = 1429582984839;
Date date1 = new Date(unixSeconds);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy h:mm:ss a");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+1"));
String formattedDate = sdf.format(date1);
System.out.println(formattedDate);
Your number 1429582984839 is already in milliseconds. There is no need to multiply it by 1000. That's all you need to know.
(For anyone who wants to confirm in JavaScript, try: new Date(1429582984839) --> "2015-04-21T02:23:04.839Z")
To make a long type variables, you need to suffix 'L' or 'l' in the number. Otherwise it will take it is an integer.
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public void demoMethod() {
long unixSeconds = 1333372339860L; // suffix L
Date date = new Date(unixSeconds*1000L);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
sdf.setTimeZone(TimeZone.getTimeZone("GMT-4"));
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
}
Try this code, It will work. If it is useful or correct. Please mark it useful or correct answer.
use this code it is much simpler and easier.
import java.sql.TimeStamp;
long unixSeconds = 1333372339860L; // suffix L
java.util.Date date= new java.util.Date(unixSeconds*1000L);
System.out.println(new Timestamp(date.getTime()));
1333372339860 / 60 /60 /24 / 365 = 42280
Plus 1970 = 44250
So the program is correct (my calculation ignores leap years).
Where did you get the number from ?

Categories