Current date from BlackBerry - date

I am developing an application which needs the current date from the device, but it only needs day-of-week, month, and day-of-month, like Friday October 14
I have tried this code with Calendar. How do I convert Date to String? Is this possible to get date in this format?
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
System.out.println("Date" + c.getTime());
and my output : `Fri Oct 14 16:17:03 Asia/Calcutta 2011`

You could use SimpleDateFormat:
SimpleDateFormat fmt = new SimpleDateFormat("EEEE MMMM dd");
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
System.out.print("Date ");
System.out.println(fmt.format(c.getTime()));
If you need those values in different Strings it gets a little bit more complicated (using DateFormatSymbols to get the month/weekday names):
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
DateFormatSymbols dateSymbols = new DateFormatSymbols();
String[] monthsText = dateSymbols.getMonths();
String[] weekdaysText = dateSymbols.getWeekdays();
String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH));
String month = monthsText[c.get(Calendar.MONTH)];
String weekday = weekdaysText[c.get(Calendar.DAY_OF_WEEK)];
System.out.format("day: %s, month: %s, weekday: %s", day, month, weekday);

Related

Add Days Google Script

I wondered if anyone could help. I have a script where I am pulling out data from a spreadsheet list, where this is a match for this week (basically an events list, to produce a weekly agenda). I will use a for loop to increment the days to add on, but I am just trying to make it work for one day for now...
The first column is the data in format dd/mm/yyy
I am trying to take today's increment by 1 and then search through the list to find a match. The searching etc, I can make work, but the date part is just not playing. I wondered if anyone could advise.
E.g. Date Column A:
06/07/2021
06/07/2021
01/11/2021
01/11/2021
01/11/2021
01/11/2021
02/09/2021
02/09/2021
var selectedDate = row[0];
selectedDate = Utilities.formatDate(new Date(selectedDate), "GMT+1", "dd/MM/yyyy");
var currdate = new Date();
currdate = Utilities.formatDate(new Date(selectedDate), "GMT+1", "dd/MM/yyyy");
var daystochange = 1;
var newdate = new Date(currdate.getFullYear, currdate.getMonth, currdate.getDay+daystochange );
Could anyone help?
Thanks
Only use Utilities.formatDate() to output dates, not to work with dates.
The JavaScript date object has all you need to work with dates and compare. When you use the Utilities function it converts it to a string, and so you lose all the functionality of the Date object.
Also bear in mind that if you have dates, that are formatted as dates in your sheet, they will automatically be returned as Date objects.
For example, if your sheet has a date in cell A1
var date = Sheet.getRange("A1").getValue()
date instanceof Date // true
Once you have your date, if you want to add one day to it, you can take an approach similar to what you have already done:
var selectedDate = new Date(2021, 1, 15)
var newdate = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), selectedDate.getDate() + 1);
console.log(newdate) // Tue Feb 02 2021 00:00:00
Note - use getDate to return the day of the month, getDay only returns day of the week.
To check if two dates are the same, you can write a function to compare:
function isSameDate(a, b) {
return a instanceof Date &&
b instanceof Date &&
a.getYear() === b.getYear() &&
a.getMonth() === b.getMonth() &&
a.getDate() === b.getDate()
}
This function will return true if the dates are the same.
Reference
Date

Google Scripts Timestamp - Format Output on Email

I'm not sure what I'm doing wrong here, and this is probably really simple... After scouring the net and trying hundreds of different examples found, I've come up empty handed on getting the format needed. My script works, sends the email, all values are there, but the date formats are not what we are after. So, here is what's up:
I've got a basic script that sends an HTML email from a template when a respondent submits a form. The timestamp, start (date and time), end (time only) value is needed, and is printed in the HTML email, but it's showing a full-blown timestamp output such as: "Tue Nov 03 2020 11:39:28 GMT-0700 (Mountain Standard Time)"
What I am trying to do is format the timestamp value shown in the email to this: "Tue Nov 03 2020 HH:mm"
Here is the script I am using:
function onFormSubmit(e) {
var htmlBody = HtmlService.createTemplateFromFile('email');
var rng = SpreadsheetApp.getActiveSheet().getActiveRange();
var timestamp = Utilities.formatDate(new Date(), "MST" , "MM-dd-yyyy | HH:mm:ss");
var email = rng.getValues()[0];
var body = HtmlService.createTemplateFromFile("email");
var to = 'foo#bar';
var subject = 'Activity Report ' + email[0] + '';
htmlBody.timestamp = email[0];
htmlBody.start = email[1];
htmlBody.end = email[2];
htmlBody.activityobserved = email[3];
htmlBody.summary = email[4];
htmlBody.actiontaken = email[5];
htmlBody.attachments = email[6];
var email_html = htmlBody.evaluate().getContent();
MailApp.sendEmail({
to: to,
subject: subject,
htmlBody: email_html,
replyTo:'bar#foo',
});
}
Don't forget to actually use timestamp. To get the "Tue" part in your date, you can use "EEE". I set the date formatting below as you specified in your question.
function onFormSubmit(e) {
// ...
var timestamp = Utilities.formatDate(new Date(), "MST" , "EEE MMM dd yyyy HH:mm");
// ...
htmlBody.timestamp = timestamp;
htmlBody.start = Utilities.formatDate(email[1], "MST" , "EEE MMM dd yyyy HH:mm");
htmlBody.end = Utilities.formatDate(email[2], "MST" , "EEE MMM dd yyyy HH:mm");
// ...
}
Solution:
You don't include variable timestamp in the htmlBody object. Instead you are using the original source value of it.
Replace:
htmlBody.timestamp = email[0];
with:
htmlBody.timestamp = timestamp;
Update based on your comment:
Im a little confused on how to format the start and end times though.
They are still displaying the full output.
Assuming that you have date objects in your sheet,
Replace:
htmlBody.start = email[1];
htmlBody.end = email[2];
with
htmlBody.start = Utilities.formatDate(new Date(email[1]), "MST" , "EEE MMM dd yyyy HH:mm");
htmlBody.end = Utilities.formatDate(new Date(email[2]), "MST" , "EEE MMM dd yyyy HH:mm");

Year-Week-Day in java.time?

Is there support in the java.time classes, or its extension ThreeTen-Extra, for a week dates, specifically a Year-Week-Day such as 2009-W53-7 which is Sunday 3 January 2010.
As for the year-week without the day-of-week:
My Answer to the Question, java get week of year for given a date, explains using IsoFields to handle the year-week.
The ThreeTen-Extra project that extends the java.time classes offers the YearWeek class.
But how to represent the day-of-week as well?
See the IsoFields class, which allows the week-based year and week of week-based year to be queried. There is also a dedicated formatter ISO_WEEK_DATE.
The DayOfWeek enum tells you the number of the day-of-week, 1-7 for Monday to Sunday. Call LocalDate::getDayOfWeek and then DayOfWeek::getValue.
LocalDate ld = LocalDate.now( ZoneId.of( "America/Montreal" ) ) ;
2016-12-07
int weekOfWeekBasedYear = ld.get( IsoFields.WEEK_OF_WEEK_BASED_YEAR ) ;
int yearOfWeekBasedYear = ld.get( IsoFields.WEEK_BASED_YEAR ) ;
int dayOfWeek = ld.getDayOfWeek().getValue();
Use these parts to build strings in the standard ISO 8601 week date formats.
String yearWeek = yearOfWeekBasedYear + "-W" + String.format( "%02d", weekOfWeekBasedYear ) ;
2016-W49
String yearWeekDay = yearWeek + "-" + dayOfWeek ;
2016-W49-3
Or, let the predefined DateTimeFormatter.ISO_WEEK_DATE do the work.
String ywd = ld.format( DateTimeFormatter.ISO_WEEK_DATE );
2016-W49-3
That same formatter can parse such standard strings.
String input = "2016-W49-3" ;
LocalDate ldParsed = LocalDate.parse( input , DateTimeFormatter.ISO_WEEK_DATE ) ;
2016-12-07

using datetime object as an argument

I have been struggling to understand how to use datetime objects. I want to use datetime.date instances as keys in a dictionary. I then want to be able to return dates within specified ranges using datetime.delta.
My first conundrum is when I create an object to be entered into the dictionary.
class Work_day():
'''input a workday , date and hours worked'''
def __init__(self, date, hours, rate):
self.date = datetime.date()
self.hours = hours
self.rate = rate
I want self.date to be a datetime.date object but datetime.date takes 3 argument (year, month, day) so what is the correct syntax for the def_init_ argument 'date'?
Then I assume when I change how that is written in the Work_day class then I will have to modify my code when I create instances of it in the Timesheet class e.g. in add_work_day() method
class Timesheet():
'''Represent a collection of workdays'''
def __init__(self):
self.timesheet = {}
def add_work_day(self, date, hours,rate):
'''adds a record of a work day into the timesheet dictionary'''
day = Work_day(date, hours, rate)
if day.date in self.timesheet:
print("There is already an entry for this day. ")
else:
self.timesheet[day.date] = hours, rate
I've been researching the python docs and scouring books but I'm not getting it! Need some help.
I also have a method that prints a range of the workdays in the timesheet. I made it work when I subbed the date key for a simple int. here it is (in ''' ''') with a shonky attempt at a datetime delta underneath
def show_days(self):
'''shows a user defined range of dates and the total pay for that period'''
pp = pprint.PrettyPrinter()
date_from = input("From date: ")
date_to = input("To date: ")
t = self.timesheet
total = 0
'''for dates in range(date_from, date_to + 1):
if dates in t:
total += self.sum_day(dates)
pp.pprint((dates, t[dates)])
print("Total £", total)'''
date = date_start = datetime.date(date_from)
date_end = datetime.date(date_to)
while date <= date_end:
if date in t:
print(date, t[dates])
date += datetime.timedelta(days=1)
I hope someone can find the patience to talk me through this. Cheers.
If you assign the date with self.date = datetime.date(*date), then you can create a Work_day by passing a (year,month,day) tuple:
day = Work_day((2013,5,31), 8.0, 8.25)
Alternatively, if you want the input to be a date string, use datetime.strptime, an appropriate formatting string, and the date() method to get a date object:
self.date = datetime.datetime.strptime(date,'%m/%d/%Y').date()
...
date = Work_day('5/31/2013', 8.0, 8.25)
Finally, you could just pass a date object:
day = Work_day(datetime.date(2013,5,31), 8.0, 8.25)
...
self.date = date
The Timesheet class should work after any of these changes. show_days still needs some work, but I'll leave that as an exercise. Hint: Parse the input dates with strptime.

Convert Long date to specific short date format

Convert Long date format to specific short date format.
I want to get the Date from Datepicker(Jcalander) , format to dd-mm-yyyy format and assign to String variable. I tried using codes shown below. But didnt get the date format i want.
SimpleDateFormat simpleFormat = (SimpleDateFormat) jCalendarCombo1.getDateFormat();
Date date = jCalendarCombo1.getDate();
System.out.println(date); // Prints Thu Mar 28 00:00:00 IST 2013
String s = simpleFormat.format(date);
System.out.println(s); // prints Thursday, March 28, 2013
System.out.println("Date SHORT format: " + DateFormat.getDateInstance(DateFormat.SHORT).format(date)); // prints 3/28/13
If you want a fixed, non locale dependent format, you can just create it yourself;
SimpleDateFormat shortformat = new SimpleDateFormat("dd-MM-yyyy");
String s = shortformat.format(date);
System.out.println(s); // Prints 29-03-2013