Convert currentTimeMillis to a datetime in JAVA(Spring Boot)

Spring Boot

In this tutorial I’ll show how to save Time Stamp in Database in currentTimeMillis and retrieve in Spring Boot

Want precise time for some purpose? Normally, we can save Time Stamp in Database but what if the data need to be converted into several formats?

Let’s say we need to save “2019-6-27 00:59:59” and then convert it to several formats like ’27/2019/6 00:59:59′ and ’20-JUN-1990 08:03:00′. Though “2019-6-27 00:59:59” can be converted but that’s a little bit tough. The ideal solution is to save the data in millisecond format. In millisecond format “2019-6-27 00:59:59” would be “1564167599000”

I assume you already have the datetime picker data in controller, here’s the conversion code:

String expireTime = model.attribute; //your model attribute or request parameter name
Date date = formatter.parse(expireTime);
Timestamp timestamp = new Timestamp(date.getTime());
String expireTime2 = String.valueOf(timestamp.getTime());
//That's it! We've converted '2019-6-27 00:59:59' to '1564167599000'
//Add your save logic

Now the reading part. User can’t read ‘1564167599000’, right? Let’s convert this to readable format:

String convertedExpireTime = "1564167599000";
//Create a calendar instance
Calendar calendar = Calendar.getInstance();
int mYear = calendar.get(Calendar.YEAR);
int mMonth = calendar.get(Calendar.MONTH);
int mDay = calendar.get(Calendar.DAY_OF_MONTH);
int mHour = calendar.get(Calendar.HOUR_OF_DAY);
int mMin = calendar.get(Calendar.MINUTE);
int mSec = calendar.get(Calendar.SECOND);
String readableFormat = mYear + "-" + mMonth + "-" + mDay + " " + mHour + ":"+ mMin + ":"+ mSec; // The value is now converted to 2019-6-27 0:59:59
//Add some logic

That’s all! We’re done!

If you’ve any confusion please let me know 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *