Parsing Date/Time to Localtimezone

Javascript: parse a string to Date as LOCAL time zone

Parsing of date strings using the Date constructor or Date.parse (which are essentially the same thing) is strongly recommended against.

If Date is called as a function and passed an ISO 8601 format date string without a timezone (such as 2015-11-24T19:40:00), you may get one of the following results:

  1. Pre ES5 implementaitons may treat it as anything, even NaN (such as IE 8)
  2. ES5 compliant implementations will treat it as UTC timezone
  3. ECMAScript 2015 compliant implementations will treat it as local (which is consistent with ISO 8601)

A Date object has a time value which is UTC, and an offset based on system settings. When you send a Date to output, what you see is usually the result of Date.prototype.toString, which is an implementation dependent, human readable string representing the date and time, usually in a timezone based on system settings.

The best way to parse date strings is to do it manually. If you are assured that the format is consistent and valid, then parsing an ISO format string as a local date is as simple as:

/*  @param {string} s - an ISO 8001 format date and time string**                      with all components, e.g. 2015-11-24T19:40:00**  @returns {Date} - Date instance from parsing the string. May be NaN.*/function parseISOLocal(s) {  var b = s.split(/\D/);  return new Date(b[0], b[1]-1, b[2], b[3], b[4], b[5]);}
document.write(parseISOLocal('2015-11-24T19:40:00'));

Java - Convert a given DateTime in String to local timezone

You could parse the given date string as an OffsetDateTime, then change its offset and convert it to LocalDateTime as follows

    final String dateString = "2020-04-30T09:59:00.272-05:00";
final ZonedDateTime result = ZonedDateTime.parse(dateString);
System.out.println("Given : " + result);
final LocalDateTime localDateTime = OffsetDateTime.parse(dateString)
.atZoneSameInstant(ZoneId.of("Europe/Berlin"))
.toLocalDateTime();
System.out.println("Given In Local: " + localDateTime);```

prints

Given         : 2020-04-30T09:59:00.272-05:00
Given In Local: 2020-04-30T16:59:00.272

Besides, you could also parse it to ZonedDateTime and then change the time zone, e.g.

final LocalDateTime result = ZonedDateTime.parse(dateString)
.withZoneSameInstant(ZoneId.of("Europe/Berlin"))
.toLocalDateTime();

Parse date without timezone to local timezone

Parse your input as LocalDateTime.

LocalDateTime ldt = LocalDateTime.parse( "2020-01-31 04:38:00".replace( " " , "T" ) ) ;

You claim to know for sure that the string represents a moment as seen in UTC, that is, with an offset-from-UTC of zero hours-minutes-seconds.

OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;

If you want to adjust into a time zone, apply a ZoneId to get a ZonedDateTime object.

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;

I do not know why you involved Locale. The Locale class has nothing to do with date-time values. A Locale is only needed if you are localizing when generating text to represent your date-time value, to determine names of month or day-of-week, and issues of capitalization, punctuation, abbreviation, order of parts.

Locale locale = Locale.JAPAN ; 
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( locale ) ;
String output = zdt.format( f ) ;

See this code run live at IdeOne.com.

Both odt & zdt represent the same moment, the same simultaneous point on the timeline, but differ in their wall-clock time. People in Tunisia set their clocks one hour ahead of UTC. So in zdt we see the time-of-day as 5:38 rather than 4:38.

ldt.toString() = 2020-01-31T04:38
odt.toString() = 2020-01-31T04:38Z
zdt.toString() = 2020-01-31T05:38+01:00[Africa/Tunis]
output = 2020年1月31日金曜日 5時38分00秒 中央ヨーロッパ標準時

how to force Date.parse() in javascript to convert to local time and date instead of UTC

By the ECMAScript spec, you simply need to use a T instead of a space to separate the date and time parts.

const t = Date.parse('2021-02-22' + 'T' + '13:00');
console.log(t); // result will differ depending on local time zone

Convert a GMT datetime to local timezone datetime

The problem is that the source system took the pure date value, but added time at midnight, then converted that to UTC, but you want the pure date value in a java.util.Date, which by default prints in your local time zone, i.e. the JVM's default time zone.

So, you have to parse the string, revert the value back to the time zone of the source system, the treat that local time as a time in your own JVM's default time zone.

You can do that like this, showing all the intermediate types:

String sourceStr = "2020-01-11T23:00:00.000Z";
ZoneId sourceTimeZone = ZoneOffset.ofHours(1); // Use real zone of source, e.g. ZoneId.of("Europe/Paris");

// Parse Zulu date string as zoned date/time in source time zone
Instant sourceInstant = Instant.parse(sourceStr);
ZonedDateTime sourceZoned = sourceInstant.atZone(sourceTimeZone);

// Convert to util.Date in local time zone
ZonedDateTime localZoned = sourceZoned.withZoneSameLocal(ZoneId.systemDefault());
Instant localInstant = localZoned.toInstant();
Date localDate = Date.from(localInstant); // <== This is your desired result

// Print value in ISO 8601 format
String localStr = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").format(localDate);
System.out.println(localStr);

Output

2020-01-12T00:00:00.000

The code can of course be merged together:

String input = "2020-01-11T23:00:00.000Z";

Date date = Date.from(Instant.parse(input).atZone(ZoneOffset.ofHours(1))
.withZoneSameLocal(ZoneId.systemDefault()).toInstant());

System.out.println(date);

Output

Sun Jan 12 00:00:00 EST 2020

As you can see, the date value is correct, even though I'm in the US Eastern time zone.

Java Date Time conversion to given timezone

with the help of @ole v.v's explanation i have separated the datetime value for two
1. time
2. timezone

then i used this coding to extract the datetime which is related to the given timezone

//convert datetime to give timezone 
private static String DateTimeConverter (String timeVal, String timeZone)
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

SimpleDateFormat offsetDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

offsetDateFormat2.setTimeZone(TimeZone.getTimeZone(timeZone));
String result =null;
try {
result = offsetDateFormat2.format(format.parse(timeVal));
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return result;
}

datetime parsing without changing timezone

SimpleDateFormat allows you to specify the TimeZone to parse from.

eg:
formatter.setTimeZone(TimeZone.getTimeZone("America/New_York"));

Or if you just wanted a custom GMT-5 time zone (ie: without any location specific DST rules):
formatter.setTimeZone(TimeZone.getTimeZone("GMT-5"));

Edit: having had a chance to look at the second part of your problem, and take a look at the calendar api you are using - and assuming the google api classes you are using here are those in the com.google.apis groupId, google-api-services-calendar artifactId, then you want to also specify the TimeZone of offset when instantiating the com.google.api.client.util.DateTime instance.

Using the SimpleDateFormat with the specified timezone for New York to parse the string "2/19/2019 4:15 PM" into a date will get you a java.util.Date that wraps the long value 1550610900000 (regardless of your actual local timezone).Note that if you print the toString() of that Date it will give a date in your local machine's timezone. eg: for me its says "Wed Feb 20 05:15:00 SGT 2019".

The DateTime extracts that long value from the specified Date via getTime() and stores it as a long internally.

DateTime (or at least the version of the DateTime class I quickly grabbed to experiment with (v3-rev364-1.25.0) ) also has a constructor that takes a TimeZone whence it extracts an offset from UTC via getOffset(). If you don't pass it one it will use TimeZone.getDefault().getOffset(value) internally. Later when its toString() is invoked it will render it using the offset it stored (which it got from the timezone).

Example:

SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm a", Locale.US);
formatter.setTimeZone(TimeZone.getTimeZone("America/New_York"));
Date date = formatter.parse("2/19/2019 4:15 PM");

DateTime startDateTimeNY = new DateTime(date,TimeZone.getTimeZone("America/New_York"));
DateTime startDateTimeSG = new DateTime(date,TimeZone.getTimeZone("Asia/Singapore"));
DateTime startDateTimeNBO = new DateTime(date,TimeZone.getTimeZone("Africa/Nairobi"));
System.out.println(startDateTimeNY); //prints 2019-02-19T16:15:00.000-05:00
System.out.println(startDateTimeSG); //prints 2019-02-20T05:15:00.000+08:00
System.out.println(startDateTimeNBO); //prints 2019-02-20T00:15:00.000+03:00

(You can see the differing local times in the output there)

I haven't had time to confirm it, but looks like EventDateTime is just using the toString() from the DateTime for the dateTime value (if you don't have a JsonFactory set in it). (The TimeZone it stores it for another purpose?)

TLDR: Specifiying a TimeZone on the SimpleDateFormat lets you reads the date correctly from its source timezone, and to format the output as desired you also need to change your call to DateTime constructor to use the desired timezone thusly:

DateTime startDateTime = new DateTime(date,TimeZone.getTimeZone("America/New_York"));

Convert UTC date string like 2022-07-07T08:17:12.117000 to your local Timezone in Kotlin and Java. Alternative to Moment library available in react

In JAVA

public String TimeConverter(String date) throws ParseException {
String dateStr = date;
try {
@SuppressLint("SimpleDateFormat") SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = formatter.parse(dateStr);
@SuppressLint("SimpleDateFormat") SimpleDateFormat dateformatter = new SimpleDateFormat("MMM-dd-yyyy hh:mm a");
dateformatter.setTimeZone(TimeZone.getDefault());
dateStr = dateformatter.format(value);
} catch (Exception e) {
dateStr = "00-00-0000 00:00";
}
return dateStr;
}

In Kotlin

fun main() {
var newdate = "2022-07-07T08:17:12.117000";
try {

val formatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")

formatter.timeZone = TimeZone.getTimeZone("UTC")
val value = formatter.parse(newdate.toString())
val dateFormatter = SimpleDateFormat("MMM-dd-yyyy hh:mm a") //this format changeable
dateFormatter.timeZone = TimeZone.getDefault()
newdate = dateFormatter.format(value)
//Log.d("ourDate", ourDate);
} catch (e: Exception) {
newdate = "00-00-0000 00:00"
}
println(newdate)
}

May this help!
I have been keep digging for this that's why i want to share so that it can help someone like me.

Just remember to change the simple date format pattern according to your date pattern.



Related Topics



Leave a reply



Submit