1use alloc::{format, string::String as RustString, vec, vec::Vec};
2
3use chrono::{DateTime, Datelike, NaiveDate, TimeZone as ChronoTimeZone, Timelike, Utc};
4use jvm::{ClassInstanceRef, Jvm, Result, runtime::JavaLangString};
5use jvm_class_proto::{JavaFieldProto, JavaMethodProto};
6use jvm_types::{ClassAccessFlags, FieldAccessFlags, MethodAccessFlags};
7
8use crate::{
9 RuntimeClassProto, RuntimeContext,
10 classes::java::{
11 lang::{String, StringBuffer},
12 text::{FieldPosition, ParsePosition},
13 util::{Calendar, Date, Locale, TimeZone},
14 },
15};
16
17#[derive(Clone)]
18enum DateToken {
19 Literal(RustString),
20 Field(char, usize),
21}
22
23pub struct SimpleDateFormat;
25
26impl SimpleDateFormat {
27 pub fn as_proto() -> RuntimeClassProto {
28 RuntimeClassProto {
29 name: "java/text/SimpleDateFormat",
30 parent_class: Some("java/text/DateFormat"),
31 interfaces: vec![],
32 methods: vec![
33 JavaMethodProto::new("<init>", "()V", Self::init, MethodAccessFlags::PUBLIC),
34 JavaMethodProto::new("<init>", "(Ljava/lang/String;)V", Self::init_with_pattern, MethodAccessFlags::PUBLIC),
35 JavaMethodProto::new(
36 "<init>",
37 "(Ljava/lang/String;Ljava/util/Locale;)V",
38 Self::init_with_pattern_and_locale,
39 MethodAccessFlags::PUBLIC,
40 ),
41 JavaMethodProto::new(
42 "format",
43 "(Ljava/util/Date;Ljava/lang/StringBuffer;Ljava/text/FieldPosition;)Ljava/lang/StringBuffer;",
44 Self::format,
45 MethodAccessFlags::PUBLIC,
46 ),
47 JavaMethodProto::new(
48 "parse",
49 "(Ljava/lang/String;Ljava/text/ParsePosition;)Ljava/util/Date;",
50 Self::parse,
51 MethodAccessFlags::PUBLIC,
52 ),
53 JavaMethodProto::new("applyPattern", "(Ljava/lang/String;)V", Self::apply_pattern, MethodAccessFlags::PUBLIC),
54 JavaMethodProto::new("toPattern", "()Ljava/lang/String;", Self::to_pattern, MethodAccessFlags::PUBLIC),
55 ],
56 fields: vec![JavaFieldProto::new("pattern", "Ljava/lang/String;", FieldAccessFlags::PRIVATE)],
57 access_flags: ClassAccessFlags::PUBLIC,
58 }
59 }
60
61 fn tokenize_pattern(pattern: &str) -> Option<Vec<DateToken>> {
62 let characters: Vec<char> = pattern.chars().collect();
63 let mut tokens = Vec::new();
64 let mut literal = RustString::new();
65 let mut quoted = false;
66 let mut index = 0;
67 while index < characters.len() {
68 let character = characters[index];
69 if character == '\'' {
70 if index + 1 < characters.len() && characters[index + 1] == '\'' {
71 literal.push('\'');
72 index += 2;
73 continue;
74 }
75 quoted = !quoted;
76 index += 1;
77 continue;
78 }
79 if !quoted && character.is_ascii_alphabetic() {
80 if !matches!(
81 character,
82 'G' | 'y' | 'M' | 'd' | 'h' | 'H' | 'm' | 's' | 'S' | 'E' | 'D' | 'F' | 'w' | 'W' | 'a' | 'k' | 'K' | 'z'
83 ) {
84 return None;
85 }
86 if !literal.is_empty() {
87 tokens.push(DateToken::Literal(core::mem::take(&mut literal)));
88 }
89 let mut count = 1;
90 while index + count < characters.len() && characters[index + count] == character {
91 count += 1;
92 }
93 tokens.push(DateToken::Field(character, count));
94 index += count;
95 continue;
96 }
97 literal.push(character);
98 index += 1;
99 }
100 if quoted {
101 return None;
102 }
103 if !literal.is_empty() {
104 tokens.push(DateToken::Literal(literal));
105 }
106 Some(tokens)
107 }
108
109 fn parse_number(characters: &[char], index: &mut usize, maximum_digits: Option<usize>) -> Option<i32> {
110 let start = *index;
111 let mut value = 0i32;
112 while *index < characters.len() && characters[*index].is_ascii_digit() && maximum_digits.is_none_or(|maximum| *index - start < maximum) {
113 value = value.checked_mul(10)?.checked_add(characters[*index].to_digit(10)? as i32)?;
114 *index += 1;
115 }
116 if *index == start { None } else { Some(value) }
117 }
118
119 fn starts_with_ignore_ascii_case(characters: &[char], index: usize, value: &str) -> bool {
120 let value: Vec<char> = value.chars().collect();
121 characters
122 .get(index..index + value.len())
123 .is_some_and(|candidate| candidate.iter().zip(value).all(|(left, right)| left.eq_ignore_ascii_case(&right)))
124 }
125
126 fn parse_timestamp(tokens: &[DateToken], characters: &[char], start: usize, default_offset: i32) -> core::result::Result<(i64, usize), usize> {
127 let months = [
128 ("January", "Jan"),
129 ("February", "Feb"),
130 ("March", "Mar"),
131 ("April", "Apr"),
132 ("May", "May"),
133 ("June", "Jun"),
134 ("July", "Jul"),
135 ("August", "Aug"),
136 ("September", "Sep"),
137 ("October", "Oct"),
138 ("November", "Nov"),
139 ("December", "Dec"),
140 ];
141 let weekdays = [
142 ("Sunday", "Sun"),
143 ("Monday", "Mon"),
144 ("Tuesday", "Tue"),
145 ("Wednesday", "Wed"),
146 ("Thursday", "Thu"),
147 ("Friday", "Fri"),
148 ("Saturday", "Sat"),
149 ];
150
151 let mut index = start;
152 let mut era = 1;
153 let mut year = 1970;
154 let mut month = 1;
155 let mut day = 1;
156 let mut ordinal = None;
157 let mut month_set = false;
158 let mut day_set = false;
159 let mut hour = 0;
160 let mut twelve_hour = None;
161 let mut am_pm = 0;
162 let mut minute = 0;
163 let mut second = 0;
164 let mut millisecond = 0;
165 let mut offset = default_offset;
166
167 for token in tokens {
168 match token {
169 DateToken::Literal(literal) => {
170 let value: Vec<char> = literal.chars().collect();
171 if !characters[index..].starts_with(&value) {
172 return Err(index);
173 }
174 index += value.len();
175 }
176 DateToken::Field(character, count) => match character {
177 'G' => {
178 if Self::starts_with_ignore_ascii_case(characters, index, "AD") {
179 era = 1;
180 index += 2;
181 } else if Self::starts_with_ignore_ascii_case(characters, index, "BC") {
182 era = 0;
183 index += 2;
184 } else {
185 return Err(index);
186 }
187 }
188 'y' => {
189 let value = Self::parse_number(characters, &mut index, if *count > 1 { Some(*count) } else { None }).ok_or(index)?;
190 year = if *count == 2 {
191 if value <= 69 { 2000 + value } else { 1900 + value }
192 } else {
193 value
194 };
195 }
196 'M' if *count >= 3 => {
197 let mut parsed = None;
198 for (position, (full, short)) in months.iter().enumerate() {
199 let candidate = if *count >= 4 { *full } else { *short };
200 if Self::starts_with_ignore_ascii_case(characters, index, candidate) {
201 parsed = Some((position as i32 + 1, candidate.len()));
202 break;
203 }
204 }
205 let Some((value, length)) = parsed else {
206 return Err(index);
207 };
208 month = value;
209 month_set = true;
210 index += length;
211 }
212 'M' => {
213 month = Self::parse_number(characters, &mut index, if *count > 1 { Some(*count) } else { None }).ok_or(index)?;
214 month_set = true;
215 }
216 'd' => {
217 day = Self::parse_number(characters, &mut index, if *count > 1 { Some(*count) } else { None }).ok_or(index)?;
218 day_set = true;
219 }
220 'H' => hour = Self::parse_number(characters, &mut index, if *count > 1 { Some(*count) } else { None }).ok_or(index)?,
221 'k' => {
222 let value = Self::parse_number(characters, &mut index, if *count > 1 { Some(*count) } else { None }).ok_or(index)?;
223 if !(1..=24).contains(&value) {
224 return Err(index);
225 }
226 hour = value % 24;
227 }
228 'h' | 'K' => {
229 let value = Self::parse_number(characters, &mut index, if *count > 1 { Some(*count) } else { None }).ok_or(index)?;
230 twelve_hour = Some((*character, value));
231 }
232 'm' => minute = Self::parse_number(characters, &mut index, if *count > 1 { Some(*count) } else { None }).ok_or(index)?,
233 's' => second = Self::parse_number(characters, &mut index, if *count > 1 { Some(*count) } else { None }).ok_or(index)?,
234 'S' => millisecond = Self::parse_number(characters, &mut index, Some((*count).max(1))).ok_or(index)?,
235 'E' => {
236 let mut consumed = None;
237 for (full, short) in weekdays {
238 for candidate in [full, short] {
239 if Self::starts_with_ignore_ascii_case(characters, index, candidate) {
240 consumed = Some(candidate.len());
241 break;
242 }
243 }
244 if consumed.is_some() {
245 break;
246 }
247 }
248 let Some(length) = consumed else {
249 return Err(index);
250 };
251 index += length;
252 }
253 'D' => ordinal = Some(Self::parse_number(characters, &mut index, if *count > 1 { Some(*count) } else { None }).ok_or(index)?),
254 'F' | 'w' | 'W' => {
255 let _ = Self::parse_number(characters, &mut index, if *count > 1 { Some(*count) } else { None }).ok_or(index)?;
256 }
257 'a' => {
258 if Self::starts_with_ignore_ascii_case(characters, index, "AM") {
259 am_pm = 0;
260 index += 2;
261 } else if Self::starts_with_ignore_ascii_case(characters, index, "PM") {
262 am_pm = 1;
263 index += 2;
264 } else {
265 return Err(index);
266 }
267 }
268 'z' => {
269 if Self::starts_with_ignore_ascii_case(characters, index, "GMT")
270 || Self::starts_with_ignore_ascii_case(characters, index, "UTC")
271 {
272 index += 3;
273 } else {
274 return Err(index);
275 }
276 offset = 0;
277 if index < characters.len() && matches!(characters[index], '+' | '-') {
278 let sign = if characters[index] == '-' { -1 } else { 1 };
279 index += 1;
280 let hours = Self::parse_number(characters, &mut index, Some(2)).ok_or(index)?;
281 if index >= characters.len() || characters[index] != ':' {
282 return Err(index);
283 }
284 index += 1;
285 let minutes = Self::parse_number(characters, &mut index, Some(2)).ok_or(index)?;
286 if hours > 23 || minutes > 59 {
287 return Err(index);
288 }
289 offset = sign * (hours * 60 + minutes) * 60 * 1000;
290 }
291 }
292 _ => return Err(index),
293 },
294 }
295 }
296
297 if let Some((kind, value)) = twelve_hour {
298 hour = match kind {
299 'h' if (1..=12).contains(&value) => value % 12 + am_pm * 12,
300 'K' if (0..=11).contains(&value) => value + am_pm * 12,
301 _ => return Err(index),
302 };
303 }
304 if era == 0 {
305 year = 1 - year;
306 }
307 if let Some(ordinal) = ordinal.filter(|_| !month_set && !day_set) {
308 let Some(date) = NaiveDate::from_yo_opt(year, ordinal as u32) else {
309 return Err(index);
310 };
311 month = date.month() as i32;
312 day = date.day() as i32;
313 }
314 if !(1..=12).contains(&month)
315 || !(1..=31).contains(&day)
316 || !(0..=23).contains(&hour)
317 || !(0..=59).contains(&minute)
318 || !(0..=59).contains(&second)
319 || !(0..=999).contains(&millisecond)
320 {
321 return Err(index);
322 }
323 let Some(date_time) = Utc
324 .with_ymd_and_hms(year, month as u32, day as u32, hour as u32, minute as u32, second as u32)
325 .single()
326 else {
327 return Err(index);
328 };
329 let Some(timestamp) = date_time
330 .timestamp_millis()
331 .checked_add(i64::from(millisecond))
332 .and_then(|value| value.checked_sub(i64::from(offset)))
333 else {
334 return Err(index);
335 };
336 Ok((timestamp, index))
337 }
338
339 fn date_field(character: char) -> Option<i32> {
340 match character {
341 'G' => Some(0),
342 'y' => Some(1),
343 'M' => Some(2),
344 'd' => Some(3),
345 'k' => Some(4),
346 'H' => Some(5),
347 'm' => Some(6),
348 's' => Some(7),
349 'S' => Some(8),
350 'E' => Some(9),
351 'D' => Some(10),
352 'F' => Some(11),
353 'w' => Some(12),
354 'W' => Some(13),
355 'a' => Some(14),
356 'h' => Some(15),
357 'K' => Some(16),
358 'z' => Some(17),
359 _ => None,
360 }
361 }
362
363 async fn init(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<()> {
364 let pattern = JavaLangString::from_rust_string(jvm, "M/d/yy h:mm a").await?;
365 jvm.invoke_special(&this, "java/text/SimpleDateFormat", "<init>", "(Ljava/lang/String;)V", (pattern,))
366 .await
367 }
368
369 async fn init_with_pattern(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>, pattern: ClassInstanceRef<String>) -> Result<()> {
370 let locale: ClassInstanceRef<Locale> = jvm.invoke_static("java/util/Locale", "getDefault", "()Ljava/util/Locale;", ()).await?;
371 jvm.invoke_special(
372 &this,
373 "java/text/SimpleDateFormat",
374 "<init>",
375 "(Ljava/lang/String;Ljava/util/Locale;)V",
376 (pattern, locale),
377 )
378 .await
379 }
380
381 async fn init_with_pattern_and_locale(
382 jvm: &Jvm,
383 _: &mut RuntimeContext,
384 mut this: ClassInstanceRef<Self>,
385 pattern: ClassInstanceRef<String>,
386 locale: ClassInstanceRef<Locale>,
387 ) -> Result<()> {
388 if pattern.is_null() || locale.is_null() {
389 return Err(jvm.exception("java/lang/NullPointerException", "pattern or locale").await);
390 }
391 let value = JavaLangString::to_rust_string(jvm, &pattern).await?;
392 if Self::tokenize_pattern(&value).is_none() {
393 return Err(jvm.exception("java/lang/IllegalArgumentException", "Illegal pattern character").await);
394 }
395 let _: () = jvm.invoke_special(&this, "java/text/DateFormat", "<init>", "()V", ()).await?;
396 jvm.put_field(&mut this, "java/text/SimpleDateFormat", "pattern", "Ljava/lang/String;", pattern)
397 .await
398 }
399
400 async fn apply_pattern(jvm: &Jvm, _: &mut RuntimeContext, mut this: ClassInstanceRef<Self>, pattern: ClassInstanceRef<String>) -> Result<()> {
401 if pattern.is_null() {
402 return Err(jvm.exception("java/lang/NullPointerException", "pattern").await);
403 }
404 let value = JavaLangString::to_rust_string(jvm, &pattern).await?;
405 if Self::tokenize_pattern(&value).is_none() {
406 return Err(jvm.exception("java/lang/IllegalArgumentException", "Illegal pattern character").await);
407 }
408 jvm.put_field(&mut this, "java/text/SimpleDateFormat", "pattern", "Ljava/lang/String;", pattern)
409 .await
410 }
411
412 async fn to_pattern(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<ClassInstanceRef<String>> {
413 jvm.get_field(&this, "java/text/SimpleDateFormat", "pattern", "Ljava/lang/String;").await
414 }
415
416 async fn format(
417 jvm: &Jvm,
418 _: &mut RuntimeContext,
419 this: ClassInstanceRef<Self>,
420 date: ClassInstanceRef<Date>,
421 buffer: ClassInstanceRef<StringBuffer>,
422 position: ClassInstanceRef<FieldPosition>,
423 ) -> Result<ClassInstanceRef<StringBuffer>> {
424 if date.is_null() || buffer.is_null() || position.is_null() {
425 return Err(jvm.exception("java/lang/NullPointerException", "date, buffer, or position").await);
426 }
427 let pattern: ClassInstanceRef<String> = jvm
428 .get_field(&this, "java/text/SimpleDateFormat", "pattern", "Ljava/lang/String;")
429 .await?;
430 let pattern = JavaLangString::to_rust_string(jvm, &pattern).await?;
431 let Some(tokens) = Self::tokenize_pattern(&pattern) else {
432 return Err(jvm.exception("java/lang/IllegalArgumentException", "Illegal pattern").await);
433 };
434 let time: i64 = jvm.invoke_virtual(&date, "java/util/Date", "getTime", "()J", ()).await?;
435 let calendar: ClassInstanceRef<Calendar> = jvm
436 .get_field(&this, "java/text/SimpleDateFormat", "calendar", "Ljava/util/Calendar;")
437 .await?;
438 let time_zone: ClassInstanceRef<TimeZone> = jvm
439 .invoke_virtual(&calendar, "java/util/Calendar", "getTimeZone", "()Ljava/util/TimeZone;", ())
440 .await?;
441 let offset: i32 = jvm.invoke_virtual(&time_zone, "java/util/TimeZone", "getRawOffset", "()I", ()).await?;
442 let Some(adjusted) = time.checked_add(i64::from(offset)) else {
443 return Err(jvm.exception("java/lang/IllegalArgumentException", "date out of range").await);
444 };
445 let Some(date_time) = DateTime::<Utc>::from_timestamp_millis(adjusted) else {
446 return Err(jvm.exception("java/lang/IllegalArgumentException", "date out of range").await);
447 };
448
449 let months = [
450 "January",
451 "February",
452 "March",
453 "April",
454 "May",
455 "June",
456 "July",
457 "August",
458 "September",
459 "October",
460 "November",
461 "December",
462 ];
463 let short_months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
464 let weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
465 let short_weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
466 let requested_field: i32 = jvm.invoke_virtual(&position, "java/text/FieldPosition", "getField", "()I", ()).await?;
467 let base: i32 = jvm.invoke_virtual(&buffer, "java/lang/StringBuffer", "length", "()I", ()).await?;
468 let mut field_position_set = false;
469 let mut formatted = RustString::new();
470 for token in tokens {
471 match token {
472 DateToken::Literal(value) => formatted.push_str(&value),
473 DateToken::Field(character, count) => {
474 let begin = formatted.encode_utf16().count() as i32;
475 match character {
476 'G' => formatted.push_str(if date_time.year() <= 0 { "BC" } else { "AD" }),
477 'y' => {
478 let year = if date_time.year() <= 0 { 1 - date_time.year() } else { date_time.year() };
479 if count == 2 {
480 formatted.push_str(&format!("{:02}", year.rem_euclid(100)));
481 } else {
482 formatted.push_str(&format!("{year:0count$}"));
483 }
484 }
485 'M' if count >= 4 => formatted.push_str(months[date_time.month0() as usize]),
486 'M' if count == 3 => formatted.push_str(short_months[date_time.month0() as usize]),
487 'M' => formatted.push_str(&format!("{:0count$}", date_time.month())),
488 'd' => formatted.push_str(&format!("{:0count$}", date_time.day())),
489 'h' => {
490 let hour = date_time.hour() % 12;
491 formatted.push_str(&format!("{:0count$}", if hour == 0 { 12 } else { hour }));
492 }
493 'H' => formatted.push_str(&format!("{:0count$}", date_time.hour())),
494 'm' => formatted.push_str(&format!("{:0count$}", date_time.minute())),
495 's' => formatted.push_str(&format!("{:0count$}", date_time.second())),
496 'S' => formatted.push_str(&format!("{:0count$}", date_time.timestamp_subsec_millis())),
497 'E' if count >= 4 => formatted.push_str(weekdays[date_time.weekday().num_days_from_sunday() as usize]),
498 'E' => formatted.push_str(short_weekdays[date_time.weekday().num_days_from_sunday() as usize]),
499 'D' => formatted.push_str(&format!("{:0count$}", date_time.ordinal())),
500 'F' | 'W' => formatted.push_str(&format!("{:0count$}", (date_time.day() - 1) / 7 + 1)),
501 'w' => formatted.push_str(&format!("{:0count$}", date_time.iso_week().week())),
502 'a' => formatted.push_str(if date_time.hour() < 12 { "AM" } else { "PM" }),
503 'k' => formatted.push_str(&format!("{:0count$}", if date_time.hour() == 0 { 24 } else { date_time.hour() })),
504 'K' => formatted.push_str(&format!("{:0count$}", date_time.hour() % 12)),
505 'z' => {
506 if offset == 0 {
507 formatted.push_str("GMT");
508 } else {
509 let absolute = offset.unsigned_abs() / 60_000;
510 formatted.push_str(&format!(
511 "GMT{}{:02}:{:02}",
512 if offset < 0 { '-' } else { '+' },
513 absolute / 60,
514 absolute % 60
515 ));
516 }
517 }
518 _ => return Err(jvm.exception("java/lang/IllegalArgumentException", "Illegal pattern").await),
519 }
520 if !field_position_set && Self::date_field(character) == Some(requested_field) {
521 let _: () = jvm
522 .invoke_virtual(&position, "java/text/FieldPosition", "setBeginIndex", "(I)V", (base + begin,))
523 .await?;
524 let _: () = jvm
525 .invoke_virtual(
526 &position,
527 "java/text/FieldPosition",
528 "setEndIndex",
529 "(I)V",
530 (base + formatted.encode_utf16().count() as i32,),
531 )
532 .await?;
533 field_position_set = true;
534 }
535 }
536 }
537 }
538 let text = JavaLangString::from_rust_string(jvm, &formatted).await?;
539 jvm.invoke_virtual(
540 &buffer,
541 "java/lang/StringBuffer",
542 "append",
543 "(Ljava/lang/String;)Ljava/lang/StringBuffer;",
544 (text,),
545 )
546 .await
547 }
548
549 async fn parse(
550 jvm: &Jvm,
551 _: &mut RuntimeContext,
552 this: ClassInstanceRef<Self>,
553 source: ClassInstanceRef<String>,
554 position: ClassInstanceRef<ParsePosition>,
555 ) -> Result<ClassInstanceRef<Date>> {
556 if source.is_null() || position.is_null() {
557 return Err(jvm.exception("java/lang/NullPointerException", "source or position").await);
558 }
559 let pattern: ClassInstanceRef<String> = jvm
560 .get_field(&this, "java/text/SimpleDateFormat", "pattern", "Ljava/lang/String;")
561 .await?;
562 let pattern = JavaLangString::to_rust_string(jvm, &pattern).await?;
563 let Some(tokens) = Self::tokenize_pattern(&pattern) else {
564 return Err(jvm.exception("java/lang/IllegalArgumentException", "Illegal pattern").await);
565 };
566 let source = JavaLangString::to_rust_string(jvm, &source).await?;
567 let characters: Vec<char> = source.chars().collect();
568 let mut utf16_indices = Vec::with_capacity(characters.len() + 1);
569 let mut utf16_index = 0;
570 for character in &characters {
571 utf16_indices.push(utf16_index);
572 utf16_index += character.len_utf16();
573 }
574 utf16_indices.push(utf16_index);
575 let start: i32 = jvm.invoke_virtual(&position, "java/text/ParsePosition", "getIndex", "()I", ()).await?;
576 if start < 0 {
577 let _: () = jvm
578 .invoke_virtual(&position, "java/text/ParsePosition", "setErrorIndex", "(I)V", (start,))
579 .await?;
580 return Ok(ClassInstanceRef::new(None));
581 }
582 let Some(start_index) = utf16_indices.iter().position(|index| *index == start as usize) else {
583 let _: () = jvm
584 .invoke_virtual(&position, "java/text/ParsePosition", "setErrorIndex", "(I)V", (start,))
585 .await?;
586 return Ok(ClassInstanceRef::new(None));
587 };
588 let calendar: ClassInstanceRef<Calendar> = jvm
589 .get_field(&this, "java/text/SimpleDateFormat", "calendar", "Ljava/util/Calendar;")
590 .await?;
591 let time_zone: ClassInstanceRef<TimeZone> = jvm
592 .invoke_virtual(&calendar, "java/util/Calendar", "getTimeZone", "()Ljava/util/TimeZone;", ())
593 .await?;
594 let offset: i32 = jvm.invoke_virtual(&time_zone, "java/util/TimeZone", "getRawOffset", "()I", ()).await?;
595 match Self::parse_timestamp(&tokens, &characters, start_index, offset) {
596 Ok((timestamp, index)) => {
597 let _: () = jvm
598 .invoke_virtual(&position, "java/text/ParsePosition", "setIndex", "(I)V", (utf16_indices[index] as i32,))
599 .await?;
600 let _: () = jvm
601 .invoke_virtual(&position, "java/text/ParsePosition", "setErrorIndex", "(I)V", (-1,))
602 .await?;
603 Ok(jvm.new_class("java/util/Date", "(J)V", (timestamp,)).await?.into())
604 }
605 Err(error_index) => {
606 let _: () = jvm
607 .invoke_virtual(
608 &position,
609 "java/text/ParsePosition",
610 "setErrorIndex",
611 "(I)V",
612 (utf16_indices[error_index] as i32,),
613 )
614 .await?;
615 Ok(ClassInstanceRef::new(None))
616 }
617 }
618 }
619}