Format a date String java - datetime-format

I have a date String like so :- Fri Oct 31 11:30:58 GMT+05:30 2014
I want to Convert it into 2014-10-31T6:00:00 which should be after adding the offset. How can I do it?

I recommend you do it using the modern date-time API* with the following steps:
Since the given date-time string has a timezone offset value(+05:30), parse it into an OffsetDateTime object using a DateTimeFormatter object created with the applicable pattern.
Convert the obtained OffsetDateTime object into an OffsetDateTime object with ZoneOffset.UTC ensuring that the result is at the same instant. You can do it using OffsetDateTime#withOffsetSameInstant.
The default implementation of OffsetDateTime#toString omits the second and fraction-of-second if they are zero. You can format the OffsetDateTime object, obtained in the last step, using a DateTimeFormatter object created with the applicable pattern.
Your expected output also suggests that you want to ignore the seconds part. If yes, you can do so by using OffsetDateTime#truncatedTo.
Demo:
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "Fri Oct 31 11:30:58 GMT+05:30 2014";
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("E MMM d H:m:s O u", Locale.ENGLISH);
OffsetDateTime odt = OffsetDateTime.parse(strDateTime, dtfInput);
OffsetDateTime odtUtc = odt.withOffsetSameInstant(ZoneOffset.UTC);
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
String output = odtUtc.format(dtfOutput);
System.out.println(output);
// In case you want to ignore the seconds
OffsetDateTime odtUtcTruncated = odtUtc.truncatedTo(ChronoUnit.MINUTES);
output = odtUtcTruncated.format(dtfOutput);
System.out.println(output);
}
}
Output:
2014-10-31T06:00:58
2014-10-31T06:00:00
Learn more about the the modern date-time API* from Trail: Date Time.
* 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.

First you need a SimpleDateFormat with the pattern that matches your input String: "EEE MMM dd HH:mm:ss z yyyy". Take a look at: SimpleDateFromat API
SimpleDateFormat in = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Then you can parse the input String to get a corresponding Date object as follows:
Date date = in.parse("Fri Oct 31 11:30:58 GMT+05:30 2014");
Note that Date objects does not have timezone as part of its state. If you want to print the Date in UTC then you need another SimpleDateFormat to format and print the date in your required timezone.
SimpleDateFormat out = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
out.setTimeZone(TimeZone.getTimeZone("UTC"));
out.format(date);
Example: http://ideone.com/Wojec3
public static void main (String[] args) throws java.lang.Exception
{
SimpleDateFormat in = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
SimpleDateFormat out = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
out.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = in.parse("Fri Oct 31 11:30:58 GMT+05:30 2014");
System.out.println(out.format(date));
}

This should do the task, i guess.
public static void main(String args[]) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(format.format(new Date()));
}

Related

Flink Watermarks on Event Time

I'm trying to understand watermarks with Event Time.
My Code is similar with Flink Documentation WordCount example .
I did some changes to include timestamp on event and added watermarks.
Event format is: word;timestamp
The map function creates a tuple3 with word;1;timestamp.
Then it's assign a watermark strategy with timestamp assigner equals to event timestamp field.
For the following stream events:
test;1662128808294
test;1662128818065
test;1662128822434
test;1662128826434
test;1662128831175
test;1662128836581
I got the following result: (test,6) => This is correct, i sent 6 times test word.
But looking for context in ProcessFunction i see the following:
Processing Time: Fri Sep 02 15:27:20 WEST 2022
Watermark: Fri Sep 02 15:26:56 WEST 2022
Start Window: 2022 09 02 15:26:40 End Window: 2022 09 02 15:27:20
The window it's correct, it's 40 seconds window as defined, and the watermark also it's correct, it's 20 seconds less the last event timestamp (1662128836581 = Friday, September 2, 2022 3:27:16) as defined in watermark strategy.
My Question is the window processing time. The window fired exactly at end window time processing time, but shouldn't wait until watermark pass the end of window (something like processing time = end of window + 20 seconds) (Window Default Trigger Docs) ?
What i'm doing wrong? or i'm having a bad understanding about watermarks?
My Code:
public class DataStreamJob {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(1);
WatermarkStrategy<Tuple3<String, Integer, Long>> strategy = WatermarkStrategy
.<Tuple3<String, Integer, Long>>forBoundedOutOfOrderness(Duration.ofSeconds(20))
.withTimestampAssigner((event, timestamp) -> event.f2);
DataStream<Tuple2<String, Integer>> dataStream = env
.socketTextStream("localhost", 9999)
.map(new Splitter())
.assignTimestampsAndWatermarks(strategy)
.keyBy(value -> value.f0)
.window(TumblingProcessingTimeWindows.of(Time.seconds(40)))
.process(new MyProcessWindowFunction());
dataStream.print();
env.execute("Window WordCount");
}
public static class Splitter extends RichMapFunction<String, Tuple3<String, Integer, Long>> {
#Override
public Tuple3<String, Integer, Long> map(String value) throws Exception {
String[] word = value.split(";");
return new Tuple3<String, Integer, Long>(word[0], 1, Long.parseLong(word[1]));
}
}
public static class MyProcessWindowFunction extends ProcessWindowFunction<Tuple3<String, Integer, Long>, Tuple2<String, Integer>, String, TimeWindow> {
#Override
public void process(String s, ProcessWindowFunction<Tuple3<String, Integer, Long>, Tuple2<String, Integer>, String, TimeWindow>.Context context, Iterable<Tuple3<String, Integer, Long>> elements, Collector<Tuple2<String, Integer>> out) throws Exception {
Integer sum = 0;
for (Tuple3<String, Integer, Long> in : elements) {
sum++;
}
out.collect(new Tuple2<String, Integer>(s, sum));
Date date = new Date(context.window().getStart());
Date date2 = new Date(context.window().getEnd());
Date watermark = new Date(context.currentWatermark());
Date processingTime = new Date(context.currentProcessingTime());
System.out.println(context.currentWatermark());
System.out.println("Processing Time: " + processingTime);
Format format = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
System.out.println("Watermark: " + watermark);
System.out.println("Start Window: " + format.format(date) + " End Window: " + format.format(date2));
}
}
}
Thanks.
To get event time windows, you need to change
.window(TumblingProcessingTimeWindows.of(Time.seconds(40)))
to
.window(TumblingEventTimeWindows.of(Time.seconds(40)))

Full Calendar 4.x for the Vaadin Framework 14+ not displaying in 24 hours format

enter image description here I have created a FullCalendar, it is displaying the time in AM/PM. When I am adding the enteries to the calendar, I format the LocalDateTime to 24 hours format but the Calendar displays it in AM/PM format.
How I can display the Calendar entries in 24 hours format?
My Formatter is defined as:
public static final DateTimeFormatter TWENTY_FOUR_HOURS_DATE_TIME_FORMATTER =
DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm:ss", AppConstants.APP_LOCALE);
Entry entry = new Entry();
entry.setEditable(false);
entry.setTitle(game.getHomeClub() + " - " +game.getHomeTeam());
Instant now = Instant.now();
String t = LocalDateTime.of(game.getGameTime().toLocalDate(), game.getGameTime().toLocalTime())
.format(FormattingUtils.TWENTY_FOUR_HOURS_DATE_TIME_FORMATTER);
entry.setStart(calendar.getTimezone().convertToUTC(LocalDateTime.parse(t, FormattingUtils.TWENTY_FOUR_HOURS_DATE_TIME_FORMATTER)));
entry.setEnd(game.getGameTime().plus(2, ChronoUnit.HOURS));
calendar = new MyFullCalendar();
calendar.setWeekNumbersVisible(true);
calendar.setNowIndicatorShown(false);
calendar.setNumberClickable(true);
calendar.changeView(CalendarViewImpl.AGENDA_WEEK);
calendar.setLocale(Locale.GERMANY);
private void createTimedEntry(FullCalendar calendar, String title, String start, int minutes, String color) {
Entry entry = new Entry();
setValues(calendar, entry, title, start, minutes, ChronoUnit.MINUTES, color);
calendar.addEntry(entry);
}
You need to set the Locale.
#Route(value = "test")
class TestView extends Composite<Div> {
TestView() {
Locale defaultLocale = Locale.GERMANY
FullCalendar calendar = FullCalendarBuilder.create().build()
calendar.changeView(CalendarViewImpl.TIME_GRID_DAY)
calendar.setSizeFull()
RadioButtonGroup<Locale> localeSwitcher = new RadioButtonGroup()
localeSwitcher.setItems([defaultLocale, Locale.US])
localeSwitcher.addValueChangeListener({ ev ->
calendar.setLocale(localeSwitcher.value)
})
localeSwitcher.setValue(defaultLocale)
VerticalLayout layout = new VerticalLayout(localeSwitcher, calendar)
layout.setSizeFull()
content.add(layout)
}
}
Code (Groovy) above produces following calendar for German Locale:
and this for US Locale:
I know, the question is a bit old, but this answer may help anyone who is still searchting for an answer :)
Regardless of any i18n settings, you may use initial options on the server side to modifiy the event time format.
JsonObject initialOptions = Json.createObject();
JsonObject eventTimeFormat = Json.createObject();
//{ hour: 'numeric', minute: '2-digit', timeZoneName: 'short' }
eventTimeFormat.put("hour", "2-digit");
eventTimeFormat.put("minute", "2-digit");
eventTimeFormat.put("meridiem", false);
eventTimeFormat.put("hour12", false);
initialOptions.put("eventTimeFormat", eventTimeFormat);
FullCalendar calendar = FullCalendarBuilder.create()
.withInitialOptions(defaultInitialOptions)
// ...
.build();
Any initial options you can use you may obtain from the native library docs: https://fullcalendar.io/docs/eventTimeFormat (and other pages)

Format a localized date in Codename One

This question is not for generic Java, but only for Codename One.
I know that the L10NManager class provides the methods formatDateLongStyle, formatDateShortStyle, formatDateTime, formatDateTimeMedium, formatDateTimeShort, but their output is inconsistent between platforms (Simulator, Android, iOS, etc.). Moreover, even if their output could be consistent, it's not exactly as I need it.
I need to format the output localized string exactly as requested, that is: short localized day of week, day of month, long localized month, year (four digits), a minus sign with spaces (" - "), hours (24h, two digits), colon (":"), minutes. I don't want seconds, I need an output exactly in this format.
Is there any API for that in Codename One? Any hint? Thank you
Examples of patterns compatible with the Codename One SimpleDateFormat class: https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
Full implementation example to localize in Italian the date formatted as I requested.
Note that the first day to localize in the weekDays and shortWeekDays arrays is Sunday.
Form hi = new Form("Hi World", BoxLayout.y());
String[] weekDays = {"Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato"};
String[] shortWeekDays = {"Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"};
String[] months = {"Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"};
String[] shortMonths = {"Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic"};
SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
simpleDateFormat.applyPattern("EEE d MMMMMMMMMMMMMMMMMMMM yyyy - HH:mm");
simpleDateFormat.getDateFormatSymbols().setWeekdays(weekDays);
simpleDateFormat.getDateFormatSymbols().setShortWeekdays(shortWeekDays);
simpleDateFormat.getDateFormatSymbols().setMonths(months);
simpleDateFormat.getDateFormatSymbols().setShortMonths(shortMonths);
String date = simpleDateFormat.format(new Date(System.currentTimeMillis()));
hi.add(new Label(date));
hi.show();
Example of output:
Mer 11 Settembre 2019 - 11:51
SimpleDateFormat has localization support by localizing the resource bundle with the following strings:
private static final String L10N_ZONE_LONGNAME = "ZONE_LONGNAME_";
private static final String L10N_ZONE_SHORTNAME = "ZONE_SHORTNAME_";
private static final String L10N_ZONE_LONGNAME_DST = "ZONE_LONGNAME_DST_";
private static final String L10N_ZONE_SHORTNAME_DST = "ZONE_SHORTNAME_DST_";
private static final String L10N_WEEKDAY_LONGNAME = "WEEKDAY_LONGNAME_";
private static final String L10N_WEEKDAY_SHORTNAME = "WEEKDAY_SHORTNAME_";
private static final String L10N_MONTH_LONGNAME = "MONTH_LONGNAME_";
private static final String L10N_MONTH_SHORTNAME = "MONTH_SHORTNAME_";
private static final String L10N_AMPM = "AMPM_";
private static final String L10N_ERA = "ERA_";
So for instance AM/PM can be localized by defining AMPM_AM and AMPM_PM respectively.
You can also use DateFormatSymbols directly but that's a bit painful as you need to do it per SimpleDateFormat instance.

unable to generate unique extent report i have used SimpleDateFormat Class

I was trying to generate unique extent reports with using SimpleDateFormat class.But in my eclipse work directory its showing "Test-report-null.html".
in place of null it has to show date that it can generate unique, so that i can get unique reports.
DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
Date date = new Date();
// System.out.println(dateFormat.format(date)); // 2016/11/16 12:08:43
time = dateFormat.format(date);
String repName = "Test-Report-" + time + ".html";
report = new ExtentReports(System.getProperty("user.dir") + "/ExtentReport/" + repName, true);

How to convert a TimePicker Value to a unix timestamp for Windows Phone 7?

uuhm..
I have another problem.
I need to convert a TimePicker (Windows Phone 7) Value to a unix timestamp..
How is this possible?
Thanks!
This should work:
DateTime selectedTime = ((DateTime) TimePicker.Value)
public static double ConvertToUnix (DateTime selDate)
{
var unixStart = new DateTime (1970, 1, 1).ToLocalTime();
return (selDate - unixStart).TotalSeconds;
}

Resources