I'm currently working on a JavaFX project and having issues while displaying current date in a text area.
I set the date and time format by using the following code:
SimpleDateFormat Date = new SimpleDateFormat("dd/MM/yy hh/mm");
Date date = new Date();
For example, I want the current date and time to be displayed as 15/05/2021 15:03 but the textarea shows this:
SAT May 15 15:03:21 PDT 2021
Is there anyway to set date format to "dd/MM/yy hh/mm"?
*NOTE: I imported both java.text.SimpleDateFormat and java.util.Date.
The java.util.Date, java.util.Calendar,
and java.text.SimpleDateFormat classes were rushed too quickly when
Java first launched and evolved. The classes were not well designed or
implemented. Improvements were attempted, thus the deprecations you’ve
found. Unfortunately the attempts at improvement largely failed. You
should avoid these classes altogether. They are supplanted in Java 8
by new classes (Basil Bourque).
Use this instead:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yy hh:mm");
TextArea textArea = new TextArea(formatter.format(now));
Related
I want to store a Javascript Date() object in a spreadsheet with correct format according to spreadsheet's locale (SpreadsheetApp.getActive().getSpreadsheetLocale()).
Is there a way to get the country specific (date and) time format string from the spreadsheet locale?
E.g. when locale is de_DE, time format string as hh:mm
but when locale is da_DK, time format string as hh.mm
Interesting as well how to get the countries currency format.
BTW when I have date and time in de_DE and than change to da_DK, dates are reformatted (23.01.2020 -> 23/01/2020) but times are not (it stays as 22:59). Is that an error in Spreadsheet?
Dates in JavaScript have the method toLocaleDateString, which return a string formatted according to the specified locale. But this doesn't seem to work in Apps Script.
If you're open to using an Apps Script Web App for this, you could use this toLocaleDateString in your client-side script (that is, in a script tag in your HTML).
If that's not the case, I think your best option would be to create the relationship between formats and locales yourself, because Apps Script doesn't have a built-in method to achieve that. You could, for example, use a switch statement that would check the locale, and then format the date accordingly with Utilities.formatDate, the tool Apps Script uses to format dates. It could be something along the following lines:
var locale = SpreadsheetApp.getActive().getSpreadsheetLocale();
var formattedDate;
switch (locale) {
case 'de_DE':
formattedDate = Utilities.formatDate(yourDate, yourTimeZone, "hh:mm");
break;
case 'da_DK':
formattedDate = Utilities.formatDate(yourDate, yourTimeZone, "hh.mm");
break;
// ...
}
return formattedDate;
Reference:
toLocateDateString
Apps Script Web Apps
Utilities.formatDate
I hope this is of any help.
Sorry for that, however I found a function that would be worth checking out, it's toLocaleDateString() and toLocaleTimeString (), they deliver the local date and time format.
Please check
Formato fechas JavaScript.
I did the test from Google Apps Script and it throws me the following
function pruebafecha() {
var d = new Date();
var n = d.toLocaleDateString();
var h = d.toLocaleTimeString();
Logger.log(n);
Logger.log(h);
}
This is the answer(Colombia):
[20-01-24 16:47:50:286 EST] 24 de enero de 2020
[20-01-24 16:47:50:287 EST] 16:47:50 EST
A JavaScript Date object includes date, time and timezone. When Google Apps Script pass a Date object to the spreadsheet using setValue() / setValues() the value is displayed according to the cell number formatting using the spreadsheet timezone.
If the cell formatting is set to Automatic by default the date will be displayed accordingly to the spreadsheet locale.
If you want to force the cell to display a date in an specific format use Class Range setNumberFormat / setNumberFormats
If you don't want to use the above methods and don't want to rely on the spreadsheet locale and automatic cell format then instead of passing a Date object pass the value as an string prepending it with an ' (apostrophe, single quote character) to prevent that that automatic data type parsing changes the value and it's format.
Related
Javascript in Google Sheets script: help using setNumberFormat
I don't know very well the configuration of the sheet you mention. However, I share a code that I use to print the date and time of data submission of a form.
var d = new Date();
var hour = d.getHours()-1;
var min = d.getMinutes();
var day = d.getDate();
var month = d.getMonth()+1;
var year = d.getFullYear();
if (month<10) {dia = day+"/"+"0"+month+"/"+year;}
else {dia = day+"/"+month+"/"+year;}
if (min<10){time = hour+":"+"0"+min;}
else {time = hour+":"+min;}
What I do in the code is to take the values of day, month and year, I add 1 to the value of month because it takes values [0:11] => [Jan, Dec].
Then I build the format I want from date and time, you can notice that I have 1 left to the hours, because when I did the tests I noticed that the time of the script was one hour above.
I use google translate, I hope it is understood.
Currently I like to calculate the total time taken for my soap ui automation project using groovy. I tried the following approach but it doesn't work:
Date startTime= new Date()
Date EndTime= new Date()
But i unable to compare the dates since it is taking the data types as string "Sat May 18 23:54:29 IST 2019" and I am unable to find the difference.
In groovy you can use the TimeCategory utility to subtract your dates, and get a TimeDuration object representing the difference. From this object you can inspect all sort of structured time/duration information.
Also, if you have a date in a String representation you can parse it into a Date using Date.parse passing as a parameter the format of the string and the string representation itself.
The following is a working demo of all this:
import groovy.time.*
def startTimeString = "Sat May 18 00:00:00 IST 2019"
def startTime = Date.parse("E MMM dd H:m:s z yyyy", startTimeString)
def endTime = new Date()
use (TimeCategory) {
TimeDuration duration = endTime - startTime
println "[${startTimeString}] was [${duration}] ago"
}
Complete code on GitHub
Hope this helps.
I am working with Java 8 Date and Time utility. I am using the TemporalAdjuster interface and the implementations found in TemporalAdjusters to manipulate the calculations for a specific day or date.
My requirement is to calculate the day after 3 month and 2 days.
For example, today is 6th of Decemeber (i.e 2016-12-06 in YYYY-MM-DD) and after 3 months and 2 days, the date would be 8th of March, 2017 (i.e. 2017-03-08 in YYYY-MM-DD).
I tried two ways of doing this using the Date and Time utility as follows:
//First
LocalDate dayAfter3MonthsAnd2Days = LocalDate
.now()
.with(firstDayOfNextMonth()).plusMonths(2).plusDays(2);
//Second
LocalDate dayAfter3MonthsAnd2Days = LocalDate
.now()
.with(firstDayOfMonth()).plusMonths(3).plusDays(2);
Both of them returns the date as 3rd of March, 2017 (i.e. 2017-03-03) as follows:
dayAfter3MonthsAnd2Days = 2017-03-03
Is there any way i can customize the TemporalAdjusters and get the desired output? Or any other alternate to achieve the goal?
I found out that i can simply use the following:
LocalDate dayAfter3MonthsAnd2DaysNew = LocalDate
.now()
.plusMonths(3)
.plusDays(2);
Alongwith that, i can also use the custom TemporalAdjuster which uses the above same process to do manipulations as follows:
TemporalAdjuster ta = TemporalAdjusters.ofDateAdjuster(
(LocalDate d) -> d.plusMonths(3).plusDays(2));
LocalDate dayAfter3MonthsAnd2DaysCustom = LocalDate
.now()
.with(ta);
Although the previous way is simpler, but we can use more custom proceedings using ofDateAdjuster method of TemporalAdjuster.
i am doing a flex Adobe AIR Application with SQLITE Data base,in that i want to save Date in the following format DD/MM/YYYY, but in my SQLITE TABLE i gave the data type is DATE so it saved as Sun Dec 2 00:00:00 GMT+0530 2012 in this format.
why i want to save in specific format.i have two date fields START DATE and END DATE.Once i select the End DATE date field i have to count the days between them automatically.any ideas for DD/MM/YYYY format and counting the date in between the dates.
This is my code:
[Bindable] private var date1:Date;
[Bindable] private var date2:Date;
[Bindable] private var Totaldays:String;
protected function modEndDate_creationCompleteHandler(event:FlexEvent):void
{
formatter.formatString= "DD-MM-YYYY";
date1=formatter.format(newStartdate.selectedDate);
date2=formatter.format(newEndDate.selectedDate);
**Totaldays=Math.floor(Math.abs(date1 - date2)/ (24 * 60 * 60 * 1000))**
}
The error is:
Multiple markers at this line:
-1067: Implicit coercion of a value of type Date to an unrelated type Number.
-1067: Implicit coercion of a value of type Number to an unrelated type String.
Looking for help.Thanks in Advance
Regards,
Venkatesan
Save in compatible format. Format dates in GUI as you like. Look here to calculate days between: ActionScript 3.0 + Calculate timespan between two dates?
I have to use java.util.Date class as field type in a table.
But I would like to change the display format of the date field with help of joda time (confortable, prefered to use), thats why I want to convert a Date to DateTime.
I know I oversee something, because there is no such a question in stackoverflow :) but I could not find the soulution among the DateTime constructors and so on.
The reverse conversion DateTime.toDate();
exists, but what about the opposite way ?
Thanks for the answers in advance.
Cs
In Vaadin, if you want to change display format in a table without joda, you simply override the method protected String formatPropertyValue(Object rowId, Object colId,
Property property)
Here an example to do it :
Table t = new Table() {
#Override
protected String formatPropertyValue(Object rowId, Object colId,
Property property) {
Object v = property.getValue();
if (v instanceof Date) {
Date dateValue = (Date) v;
return new SimpleDateFormat("yyyy-MMMM-dd").format(dateValue);
}
return super.formatPropertyValue(rowId, colId, property);
}
};
Regards
Éric
Yes, Use Joda-Time
Definitely use Joda-Time or the java.time package in Java 8 (inspired by Joda-Time). The old java.util.Date and java.util.Calendar classes are notoriously troublesome, confusing, and outmoded.
Also, read the Wikipedia pages on UTC and ISO 8601.
Yes, Pass Date To Joda-Time Constructor
➔ Yes indeed, you can pass a java.util.Date object to the constructor of a Joda-Time DateTime object.
The API doc is a bit confusing as this apparently falls into the catch-all version of the constructor taking an java.lang.Object instance. If that Object is in fact a java.util.Date, Joda-Time will extract its millisecond-count-since-epoch and use that number as its own.
Time Zone
A DateTime constructor also assigns a time zone. By default, the JVM’s current default time zone is assigned. I recommend you always pass a desired time zone rather than rely implicitly on the default even if that means calling getDefault.
Example Code
Here is some example code in Joda-Time 2.5 showing how to pass a java.util.Date to a Joda-Time constructor.
java.util.Date date = new java.util.Date();
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTimeMontreal = new DateTime( date , zone );
DateTime dateTimeUtc = dateTimeMontreal.withZone( DateTimeZone.UTC ); // Adjust to another time zone.
Dump to console.
System.out.println( "date: " + date ); // Misleading output. A j.u.Date is in UTC but its toString method applies JVM’s current default time zone.
System.out.println( "dateTimeMontreal: " + dateTimeMontreal );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
When run.
date: Sat Oct 18 18:54:55 PDT 2014
dateTimeMontreal: 2014-10-18T21:54:55.740-04:00
dateTimeUtc: 2014-10-19T01:54:55.740Z
As shown in the Question, to go from a DateTime to java.util.Date, call toDate.
java.util.Date date = dateTimeMontreal.toDate();