Hi i am currently work on creating Desktop application using Swing.I was able to convert IST to EST time using Date class in java but not able to convert EST to IST time and it gives same EST time as IST time. Please find the below code .
ChangetoEST function is giving correct EST time from IST time.
ChangetoIST function is not giving correct IST time from EST time and showing given EST time as IST time.
public String changetoEST(String date) throws ParseException
{
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
String dateInString = date;
Date d=formatter.parse(dateInString);
TimeZone tzInAmerica = TimeZone.getTimeZone("America/New_York");
formatter.setTimeZone(tzInAmerica);
String sDateInAmerica = formatter.format(d);
Date dateInAmerica = formatter.parse(sDateInAmerica);
String a=formatter.format(dateInAmerica);
return a;
}
public String changetoIST(String date) throws ParseException
{
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
String dateInString = date;
Date d=formatter.parse(dateInString);
TimeZone tzInIndian = TimeZone.getTimeZone("Asia/Calcutta");
formatter.setTimeZone(tzInIndian);
String sDateInAmerica = formatter.format(d);
Date dateInAmerica = formatter.parse(sDateInAmerica);
String a=formatter.format(dateInAmerica);
return a;
}
The parse calls are done without you explicitly setting a time zone, which means that parsing is done using your default time zone.
Set the source time zone before parsing, parse, set time zone to target time zone, and format result.
E.g.
public static String istToEst(String dateInput) throws ParseException {
return changeTimeZone(dateInput, TimeZone.getTimeZone("Asia/Calcutta"),
TimeZone.getTimeZone("America/New_York"));
}
public static String estToIst(String dateInput) throws ParseException {
return changeTimeZone(dateInput, TimeZone.getTimeZone("America/New_York"),
TimeZone.getTimeZone("Asia/Calcutta"));
}
private static String changeTimeZone(String dateInput, TimeZone sourceTimeZone,
TimeZone targetTimeZone) throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
formatter.setTimeZone(sourceTimeZone);
Date date = formatter.parse(dateInput);
formatter.setTimeZone(targetTimeZone);
return formatter.format(date);
}
Test
String dateInput = "08/22/2016 02:21 AM";
System.out.println(dateInput);
System.out.println(istToEst("08/22/2016 02:21 AM"));
System.out.println(estToIst("08/22/2016 02:21 AM"));
Output
08/22/2016 02:21 AM
08/21/2016 04:51 PM
08/22/2016 11:51 AM
Set formatter to the source timezone before parsing (this is the step you are missing), then set it to the destination timezone before formatting, otherwise it parses it using the local timezone, which is IST for you.
Also you should just be able to return sDateInAmerica directly, you don't need to re-parse then re-format it a second time.
java.time
You are using troublesome old legacy date-time classes, now supplanted by the java.time classes.
We parse the input string as a LocalDateTime as it lacks any info about offset-from-UTC or time zone (offset plus rules for anomalies such as DST).
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/yyyy hh:mm a" );
LocalDateTime ldt = LocalDateTime.parse( input , f );
Apply a time zone to get an actual moment on the timeline, a ZonedDateTime object.
ZoneId zNewYork = ZoneId.of( "America/New_York" );
ZonedDateTime zdtNewYork = ldt.atZone( zNewYork );
To see the same moment through the lens of another time zone, another wall-clock time, adjust into another ZoneId. Notice that we are not going through another LocalDateTime as the purpose of that class is to forget any information about offset or time zone. We want the opposite, to use the info about time zone to adjust wisely between zones. So while New York is behind UTC by four hours, India is ahead of UTC by five and a half hours. So we need a total of nine and a half hour adjustment, which may include a change in date.
ZoneId zKolkata = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdtKolkata = zdtNewYork.withZoneSameInstant( zKolkata ); // Same simultaneous moments on the timeline.
Generate String
You can generate a String in any format you desire to represent the date-time value.
String output = zdtKolkata.format( f );
Generally better to let java.time automatically localize for you.
Locale l = Locale.CANADA_FRENCH; // Or Locale.US, Locale.ITALY, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM ).withLocale( l );
String output = zdtKolkata.format( f );
Related
I have been trying and trying but I'm pretty surprised as not to be able to find a solution for my simple problem.
I have a date variable which has value like this:
res0: java.util.Date = Mon Jul 15 07:50:59 AET 2019
now I want only the Date part not the time. the functions available in the Date for such are deprecated. and all the solutions I found were using Calendar instance to get today's datetime and convert it into string using SimpleDateFormat.
I don't want a string. I want a Date without the time part and a time without the date part.
tl;dr
myJavaUtilDate
.toInstant()
.atZone(
ZoneId.of( "Australia/Sydney" )
)
.toLocalDate()
For time-of-day only, without date and without time zone:
.toLocalTime()
To generate a string, call:
.format(
DateTimeFormatter
.ofLocalizedDate( FormatSyle.MEDIUM )
.withLocale( new Locale( "en" , "AU" ) )
)
Details
Immediately convert your java.util.Date from its legacy class to the modern replacement, Instant.
Instant instant = myJavaUtilDate.toInstant() ;
Both of those classes represent a moment as seen in UTC, that is, an offset of zero hours-minutes-seconds. Adjust into a time zone by which you want to perceive the date.
For any given moment the time-of-day and the date both vary by time zone around the globe. Noon in Paris is not noon in Montréal. And a new day dawns earlier in the east than in the west. You must get very clear on this to do proper date-time handling. One moment in nature can be viewed in many ways through human-created notions of time zones.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter pseudo-zones such as AET, EST, or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Australia/Sydney" ) ;
Apply to the Instant to get a ZonedDateTime. Both represent the same simultaneous moment, but are viewed with a different wall-clock time.
ZonedDateTime zdt = instant.atZone( z ) ;
Extract the date-only portion.
LocalDate ld = zdt.toLocalDate() ;
Extract the time-of-day portion.
LocalTime lt = zdt.toLocalTime() ;
Put them back together again.
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
If you need a java.util.Date again to interoperate with old code not yet updated to java.time, convert.
Date d = Date.from( zdt.toInstant() ) ;
You can use LocalDate
val input = new Date() // your date
val date = input.toInstant().atZone(ZoneId.of("Europe/Paris")).toLocalDate()
Here is a good answer: https://stackoverflow.com/a/21242111/2750966
You could use date formatter to turn it into String and parse it back to Date.
For example:
Date yourDate = ...;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat.parse(dateFormat.format(yourDate));
The new date object now only has the date part, with the time part being filled with zeroes. For a numeric solution with the same result, check out this answer. Alternatively, if you don't want the time part at all, this answer should suit you better.
We can do this using the date formatter, you can try the following code.
object DateFormatter extends App {
val sdf = new SimpleDateFormat("EEEE MMMM dd, HH:mm:ss:SSS Z yyyy", Locale.ENGLISH)
val date = new Date()
val nowDate = sdf.format(date)
println(nowDate)
// It prints date in this format Monday July 22, 23:40:07:987 +0545 2019
// Lets print the date in the format you have provided in your question
val parsedDate = sdf.parse(nowDate)
println(parsedDate)
// Now, we have same date format as yours
// Now we have to remove the time and keep the date part only, for this we can do this
val newDateFormat = new SimpleDateFormat("yyyy-MM-dd")
val dateOnly = newDateFormat.format(parsedDate)
println(dateOnly)
//Printing time only
val timeFormatter = new SimpleDateFormat("HH:mm:ss")
val timeOnly = timeFormatter.format(parsedDate)
println(timeOnly)
}
Output:
nowDate: Tuesday July 23, 07:08:05:857 +0545 2019
parsedDate: Tue Jul 23 07:08:05 NPT 2019
dateOnly: 2019-07-23
timeOnly: 07:08:05
Update
val dateNotInString = newDateFormat.parse(dateOnly)
println(dateNotInString)
Output of Update:
dateNotInString: Tue Jul 23 00:00:00 NPT 2019
Here, you can see that dateNotInString is a date object and it does not contain any time related info. Similarly, time only info can be extracted.
Second Update
We can’t have a Date without the time part and without the date part using the SimpleDateFormat with type not String but we can convert it into LocaleDate and LocaleTime.
import java.time.Instant
val instantTime = Instant.ofEpochMilli(parsedDate.getTime)
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.ZoneId
val res = LocalDateTime.ofInstant(instantTime, ZoneId.systemDefault).toLocalTime
println("localeTime " + res)
val res1 = LocalDateTime.ofInstant(parsedDate.toInstant,ZoneId.systemDefault).toLocalDate
println("localeDate " + res1)
Output of the second Update
localeTime: 18:11:30.850
localeDate: 2019-07-23
It's type is LocaleTime and LocaleDate respectively now.
Date date = new Date(res0.getTime() - (res0.getTime() % 86400000));
System.out.println(date);
Now you can use the date formatter as is with your res0 date and it will print the date only. But what I tried to do is remove the time part basically 86400000 is the number of milliseconds per day and getTime return the number of milliseconds passed since January 1, 1970, 00:00:00 GMT. So basically this is equivalent to the date at time 00:00.00 of each day. I don't know if this is what you want because Date doesn't hold 2 separate things like date and time it just has a single long.
I have a String variable called time is 2016-11-30T00:06:42+05:30
and a duration 32700 i.e 545 minutes.
I want to add duration to above string time stamp and need to calculate start time and end time.
So i want to get StartTime:00:06 and EndTime:09:05.
I tried this but doesn't work
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date = sdf.parse(startTime.toString());
Timestamp ts_now = new Timestamp(date.getTime());
System.out.println(">>>>>>"+date);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(ts_now.getTime());
cal.add(Calendar.SECOND, Integer.parseInt(Value.toString()));
Timestamp later = new Timestamp(cal.getTime().getTime());
System.out.println(">>>>>>"+later);
I tried with X ,Z but got error like
Exception in thread "main" java.text.ParseException: Unparseable date: "2016-11-30T00:06:42+05:30"
at java.text.DateFormat.parse(DateFormat.java:366)
at oneraise.radis.thread.mavenproject1.ParseJson.main(ParseJson.java:48)
I am new to java can anybody help me
Thanks
tl;dr
OffsetDateTime.parse( "2016-11-30T00:06:42+05:30" )
.plus( Duration.ofSeconds( 32_700L ) )
Details
Avoid the troublesome and confusing date-time classes such as java.util.Date and Calendar, now legacy, supplanted by the java.time classes.
Your input string complies with standard ISO 8601 formats. Such strings can be directly parsed by java.time classes with no need to specify a formatting pattern.
Parse as an OffsetDateTime object.
OffsetDateTime odt = OffsetDateTime.parse( "2016-11-30T00:06:42+05:30" );
The ZonedDateTime class used in another Answer is inappropriate here. This input string contains only an offset-from-UTC, not a full time zone such as Asia/Kolkata. So OffsetDateTime is the class to use here.
The Duration class handles your span of time, a count of seconds.
Duration d = Duration.ofSeconds( 32_700L );
Add to your date-time object.
OffsetDateTime odtLater = odt.plus( d );
Tip: To view the OffsetDateTime value in UTC, extract an Instant.
Instant instant = odt.toInstant();
Database
For database access, your JDBC 4.2 compliant driver may be able to work with java.time objects via the get/setObject methods.
If so, no need to use the old java.sql.Timestamp class or its siblings.
myPreparedStatement.setObject( … , odt );
If not, use the new conversion methods added to the old date-lime classes.
java.sql.Timestamp ts = java.sql.Timestamp.from( odt.toInstant() );
Here is the format for the string you have given
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
SimpleDateFormat outputFormat = new SimpleDateFormat("HH:mm");
Date date;
try
{
Here I've parsed the string you have given. If you want the current time, use date = new Date();
date = sdf.parse("2016-11-30T00:06:42+05:30");
System.out.println(date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
Here I've added your interval
cal.add(Calendar.SECOND, 32700);
System.out.println(cal.getTime());
String output = outputFormat.format(date);
System.out.println(output);
String output2 = outputFormat.format(cal.getTime());
System.out.println(output2);
}
catch (ParseException e)
{
e.printStackTrace();
}
Here is the output. I'm in a different timezone.
Tue Nov 29 13:06:42 CST 2016
Tue Nov 29 22:11:42 CST 2016
13:06
22:11
If in your code I change the initialization of the date format to:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
— and I set my computer’s time zone to IST, I get the following output:
>>>>>>Wed Nov 30 00:06:42 IST 2016
>>>>>>2016-11-30 09:11:42.0
Alternatively you may use the Java 8 time classes, but convert to good old Timestamp if this is what you need. Edit: I am thankful to Basil Bourque for correctly pointing out that OffsetDateTime is the class to use, and for the method for converting to timestamp. See his answer for the full explanation.
Instant laterInstant = OffsetDateTime.parse(startTime.toString())
.plusSeconds(Integer.parseInt(value.toString()))
.toInstant();
Timestamp ts = Timestamp.from(laterInstant);
System.out.println(ts);
This prints:
2016-11-30 09:11:42.0
I believe the above does what you want.
I have a string like this 2013-10-22T01:37:56. I Need to change this string into UTC Date format like this MM/dd/yyyy KK:mm:ss a. I have tried some code but it is not returning the UTC datetime.
My code is
String[] time = itsAlarmDttm.split("T");
String aFormatDate = time[0]+ " "+time[1];
String aRevisedDate = null;
try {
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final Date dateObj = sdf.parse(aFormatDate);
aRevisedDate = new SimpleDateFormat("MM/dd/yyyy KK:mm:ss a").format(dateObj);
System.out.println(aRevisedDate);
} catch (ParseException e) {
itsLogger.error("Error occured in Parsing the Data Time Object: " +e.getMessage());
} catch (Exception e) {
itsLogger.error("Error occured in Data Time Objecct: " +e.getMessage());
}
I am getting the output is MM/dd/yyyy KK:mm:ss a format. But Not UTC time format.
How to solve this issue?
Try this... Worked for me and printed 10/22/2013 01:37:56 AM Ofcourse this is your code only with little modifications.
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // This line converts the given date into UTC time zone
final java.util.Date dateObj = sdf.parse("2013-10-22T01:37:56");
aRevisedDate = new SimpleDateFormat("MM/dd/yyyy KK:mm:ss a").format(dateObj);
System.out.println(aRevisedDate);
Try to format your date with the Z or z timezone flags:
new SimpleDateFormat("MM/dd/yyyy KK:mm:ss a Z").format(dateObj);
SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
// or SimpleDateFormat sdf = new SimpleDateFormat( "MM/dd/yyyy KK:mm:ss a Z" );
sdf.setTimeZone( TimeZone.getTimeZone( "UTC" ) );
System.out.println( sdf.format( new Date() ) );
What Time Zones?
No where in your question do you mention time zone. What time zone is implied that input string? What time zone do you want for your output? And, UTC is a time zone (or lack thereof depending on your mindset) not a string format.
ISO 8601
Your input string is in ISO 8601 format, except that it lacks an offset from UTC.
Joda-Time
Here is some example code in Joda-Time 2.3 to show you how to handle time zones. Joda-Time has built-in default formatters for parsing and generating String representations of date-time values.
String input = "2013-10-22T01:37:56";
DateTime dateTimeUtc = new DateTime( input, DateTimeZone.UTC );
DateTime dateTimeMontréal = dateTimeUtc.withZone( DateTimeZone.forID( "America/Montreal" );
String output = dateTimeMontréal.toString();
As for generating string representations in other formats, search StackOverflow for "Joda format".
java.time
It’s about time someone provides the modern answer. The modern solution uses java.time, the modern Java date and time API. The classes SimpleDateFormat and Date used in the question and in a couple of the other answers are poorly designed and long outdated, the former in particular notoriously troublesome. TimeZone is poorly designed to. I recommend you avoid those.
ZoneId utc = ZoneId.of("Etc/UTC");
DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern(
"MM/dd/yyyy hh:mm:ss a zzz", Locale.ENGLISH);
String itsAlarmDttm = "2013-10-22T01:37:56";
ZonedDateTime utcDateTime = LocalDateTime.parse(itsAlarmDttm)
.atZone(ZoneId.systemDefault())
.withZoneSameInstant(utc);
String formatterUtcDateTime = utcDateTime.format(targetFormatter);
System.out.println(formatterUtcDateTime);
When running in my time zone, Europe/Copenhagen, the output is:
10/21/2013 11:37:56 PM UTC
I have assumed that the string you got was in the default time zone of your JVM, a fragile assumption since that default setting can be changed at any time from another part of your program or another programming running in the same JVM. If you can, instead specify time zone explicitly, for example ZoneId.of("Europe/Podgorica") or ZoneId.of("Asia/Kolkata").
I am exploiting the fact that you string is in ISO 8601 format, the format the the modern classes parse as their default, that is, without any explicit formatter.
I am using a ZonedDateTime for the result date-time because it allows us to format it with UTC in the formatted string to eliminate any and all doubt. For other purposes one would typically have wanted an OffsetDateTime or an Instant instead.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601
Currently the time displayed as 13:35 PM
However I want to display as 12 hour format with AM/PM, i.e 1:35 PM instead of 13:35 PM
The current code is as below
private static final int FOR_HOURS = 3600000;
private static final int FOR_MIN = 60000;
public String getTime(final Model model) {
SimpleDateFormat formatDate = new SimpleDateFormat("HH:mm a");
formatDate.setTimeZone(userContext.getUser().getTimeZone());
model.addAttribute("userCurrentTime", formatDate.format(new Date()));
final String offsetHours = String.format("%+03d:%02d", userContext.getUser().getTimeZone().getRawOffset()
/ FOR_HOURS, Math.abs(userContext.getUser().getTimeZone().getRawOffset() % FOR_HOURS / FOR_MIN));
model.addAttribute("offsetHours",
offsetHours + " " + userContext.getUser().getTimeZone().getDisplayName(Locale.ROOT));
return "systemclock";
}
Easiest way to get it by using date pattern - h:mm a, where
h - Hour in am/pm (1-12)
m - Minute in hour
a - Am/pm marker
Code snippet :
DateFormat dateFormat = new SimpleDateFormat("hh:mm a");
Read more on documentation - SimpleDateFormat java 7
Use this SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm a");
Java docs for SimpleDateFormat
use "hh:mm a" instead of "HH:mm a". Here hh for 12 hour format and HH for 24 hour format.
Live Demo
SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm:ss a");
h is used for AM/PM times (1-12).
H is used for 24 hour times (1-24).
a is the AM/PM marker
m is minute in hour
Note: Two h's will print a leading zero: 01:13 PM. One h will print without the leading zero: 1:13 PM.
Looks like basically everyone beat me to it already, but I digress
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.S aa");
String formattedDate = dateFormat.format(new Date()).toString();
System.out.println(formattedDate);
Output:
11-Sep-13 12.25.15.375 PM
// hh:mm will print hours in 12hrs clock and mins (e.g. 02:30)
System.out.println(DateTimeFormatter.ofPattern("hh:mm").format(LocalTime.now()));
// HH:mm will print hours in 24hrs clock and mins (e.g. 14:30)
System.out.println(DateTimeFormatter.ofPattern("HH:mm").format(LocalTime.now()));
// hh:mm a will print hours in 12hrs clock, mins and AM/PM (e.g. 02:30 PM)
System.out.println(DateTimeFormatter.ofPattern("hh:mm a").format(LocalTime.now()));
Using Java 8:
LocalTime localTime = LocalTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
System.out.println(localTime.format(dateTimeFormatter));
The output is in AM/PM Format.
Sample output: 3:00 PM
tl;dr
Let the modern java.time classes of JSR 310 automatically generate localized text, rather than hard-coding 12-hour clock and AM/PM.
LocalTime // Represent a time-of-day, without date, without time zone or offset-from-UTC.
.now( // Capture the current time-of-day as seen in a particular time zone.
ZoneId.of( "Africa/Casablanca" )
) // Returns a `LocalTime` object.
.format( // Generate text representing the value in our `LocalTime` object.
DateTimeFormatter // Class responsible for generating text representing the value of a java.time object.
.ofLocalizedTime( // Automatically localize the text being generated.
FormatStyle.SHORT // Specify how long or abbreviated the generated text should be.
) // Returns a `DateTimeFormatter` object.
.withLocale( Locale.US ) // Specifies a particular locale for the `DateTimeFormatter` rather than rely on the JVM’s current default locale. Returns another separate `DateTimeFormatter` object rather than altering the first, per immutable objects pattern.
) // Returns a `String` object.
10:31 AM
Automatically localize
Rather than insisting on 12-hour clock with AM/PM, you may want to let java.time automatically localize for you. Call DateTimeFormatter.ofLocalizedTime.
To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine:
The human language for translation of name of day, name of month, and such.
The cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
Here we get the current time-of-day as seen in a particular time zone. Then we generate text to represent that time. We localize to French language in Canada culture, then English language in US culture.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
LocalTime localTime = LocalTime.now( z ) ;
// Québec
Locale locale_fr_CA = Locale.CANADA_FRENCH ; // Or `Locale.US`, and so on.
DateTimeFormatter formatterQuébec = DateTimeFormatter.ofLocalizedTime( FormatStyle.SHORT ).withLocale( locale_fr_CA ) ;
String outputQuébec = localTime.format( formatterQuébec ) ;
System.out.println( outputQuébec ) ;
// US
Locale locale_en_US = Locale.US ;
DateTimeFormatter formatterUS = DateTimeFormatter.ofLocalizedTime( FormatStyle.SHORT ).withLocale( locale_en_US ) ;
String outputUS = localTime.format( formatterUS ) ;
System.out.println( outputUS ) ;
See this code run live at IdeOne.com.
10 h 31
10:31 AM
If you want current time with AM, PM in Android use
String time = new SimpleDateFormat("hh : mm a", Locale.getDefault()).format(Calendar.getInstance().getTime());
If you want current time with am, pm
String time = new SimpleDateFormat("hh : mm a", Locale.getDefault()).format(Calendar.getInstance().getTime()).toLowerCase();
OR
From API level 26
LocalTime localTime = LocalTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
String time = localTime.format(dateTimeFormatter);
Just replace below statement and it will work.
SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm a");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
This will display the date and time
//To get Filename + date and time
SimpleDateFormat f = new SimpleDateFormat("MMM");
SimpleDateFormat f1 = new SimpleDateFormat("dd");
SimpleDateFormat f2 = new SimpleDateFormat("a");
int h;
if(Calendar.getInstance().get(Calendar.HOUR)==0)
h=12;
else
h=Calendar.getInstance().get(Calendar.HOUR)
String filename="TestReport"+f1.format(new Date())+f.format(new Date())+h+f2.format(new Date())+".txt";
The Output Like:TestReport27Apr3PM.txt
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;
public class Main {
public static void main(String [] args){
try {
DateFormat parseFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm a");
String sDate = "22-01-2019 13:35 PM";
Date date = parseFormat.parse(sDate);
SimpleDateFormat displayFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
sDate = displayFormat.format(date);
System.out.println("The required format : " + sDate);
} catch (Exception e) {}
}
}
- Using java 8
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class Main
{
public static void main(String[] args)
{
String pattern = "hh:mm:ss a";
//1. LocalTime
LocalTime now = LocalTime.now();
System.out.println(now.format(DateTimeFormatter.ofPattern(pattern)));
//2. LocalDateTime
LocalDateTime nowTime = LocalDateTime.now();
System.out.println(nowTime.format(DateTimeFormatter.ofPattern(pattern)));
}
}
To put your current mobile date and time format in
Feb 9, 2018 10:36:59 PM
Date date = new Date();
String stringDate = DateFormat.getDateTimeInstance().format(date);
you can show it to your Activity, Fragment, CardView, ListView anywhere by using TextView
` TextView mDateTime;
mDateTime=findViewById(R.id.Your_TextViewId_Of_XML);
Date date = new Date();
String mStringDate = DateFormat.getDateTimeInstance().format(date);
mDateTime.setText("My Device Current Date and Time is:"+date);
`
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a");
("hh:mm:ss a") >>> Here if we don't use 'a' then 24hours will be appeared. so if we want to AM/PM in your time just add this format. if any confusion please let me know.
The records are getting saved according to time zone of US but if I want to show the same record back to user it should convert the server date time with(US Time Zone) to user's date time with user's Time Zone
If you type in google "Java date change timezone" or "Javascript date change timezone". You will have one of your results:
In Java (source: http://www.coderanch.com/t/417443/java/java/Convert-Date-one-timezone-another )
Date date = new Date();
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("CET"));
// Prints the date in the CET timezone
System.out.println(formatter.format(date));
// Set the formatter to use a different timezone
formatter.setTimeZone(TimeZone.getTimeZone("IST"));
// Prints the date in the IST timezone
System.out.println(formatter.format(date));
Javascript (source: http://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/6016329 )
// function to calculate local time
// in a different city
// given the city's UTC offset
function calcTime(city, offset) {
// create Date object for current location
d = new Date();
// convert to msec
// add local time zone offset
// get UTC time in msec
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
nd = new Date(utc + (3600000*offset));
// return time as a string
return "The local time in " + city + " is " + nd.toLocaleString();
}
// get Bombay time
alert(calcTime('Bombay', '+5.5'));
java.time
The old date-time classes are poorly designed, confusing, and troublesome. Avoid them.
Use modern classes: the java.time framework built into Java 8 and later. Find back-ports for earlier Java 6 & 7 and for Android.
An Instant is a moment on the timeline in UTC.
Instant now = Instant.now();
Apply a time zone (ZoneId) to get a ZonedDateTime.
Never use the 3-4 letter zone abbreviations such as EST or IST. They are neither standardized nor unique(!). Use proper time zone names, built in a continent/region format such as Asia/Kolkata, Pacific/Auckland, America/Los_Angeles.
ZoneId zoneId_Montreal = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt_Montreal = ZonedDateTime.ofInstant( instant , zoneId_Montreal );
Apply a different time zone to generate another ZonedDateTime adjusted to that time zone. Call withZoneSameInstant.
ZoneId zoneId_Paris = ZoneId.of( "Europe/Paris" ); // Or "Asia/Kolkata", etc.
ZonedDateTime zdt_Paris = zdt_Montreal.withZoneSameInstant( zoneId_Paris );
If you want to go back to UTC, ask for an Instant.
Instant instant = zdt_Paris.toInstant();
TimeZone fromTimezone =TimeZone.getTimeZone(from);
TimeZone toTimezone=TimeZone.getTimeZone(to);
long fromOffset = fromTimezone.getOffset(calendar.getTimeInMillis());
long toOffset = toTimezone.getOffset(calendar.getTimeInMillis());
long convertedTime = calendar.getTimeInMillis() - (fromOffset - toOffset);
//Convert date from one zone to another
/*
$zone_from='Asia/Kolkata';
$zone_to='America/Phoenix';
date_default_timezone_set($zone_from);
$convert_date="2016-02-26 10:35:00";
echo $finalDate=zone_conversion_date($convert_date, $zone_from, $zone_to);
*/
function zone_conversion_date($time, $cur_zone, $req_zone)
{
date_default_timezone_set("GMT");
$gmt = date("Y-m-d H:i:s");
date_default_timezone_set($cur_zone);
$local = date("Y-m-d H:i:s");
date_default_timezone_set($req_zone);
$required = date("Y-m-d H:i:s");
/* return $required; */
$diff1 = (strtotime($gmt) - strtotime($local));
$diff2 = (strtotime($required) - strtotime($gmt));
$date = new DateTime($time);
$date->modify("+$diff1 seconds");
$date->modify("+$diff2 seconds");
return $timestamp = $date->format("Y-m-d H:i:s");
}
Code To Get Berlin Time and Convert it into UTC Time
Calendar sc = Calendar.getInstance(TimeZone.getTimeZone("Europe/Berlin"));
String strt = null;
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
sf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
sc.set(sc.get(Calendar.YEAR),sc.get(Calendar.MONTH), sc.get(Calendar.DATE),sc.get(Calendar.HOUR) , sc.get(Calendar.MINUTE));
strt = sf.format(sc.getTime());
System.out.println("Start :"+strt);