Formatting Date in Spreadsheet - datetime

I have a column in spreadsheet that is 'date'.
When I retrieve the date with the following code,
for (var i = 1; i < data.length; ++i) {
var row = data[i];
var date= row[0];
Logger.log(date);
I get
Wed Nov 12 2014 00:00:00 GMT+0800 (HKT)
Is there a way to just show the output as
Wed Oct 15 2014
I tried converting to JSON since it is an object, so that I can use substring
startDate = JSON.stringify(startDate);
startDate = startDate.substring(0, 14);
But it doesn't output correctly.
"2014-11-12T16:00:00.000Z"

Use formatDate() from the "Utilities" class:
var formattedDate = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd'T'HH:mm:ss'Z'");
https://developers.google.com/apps-script/reference/utilities/utilities#formatDate(Date,String,String)

Did you try using "formatDate" in Utilities class
formatDate(date, timeZone, format)
try doing this:
var dateToFormat = row[0];
var formattedDate = Utilities.formatDate(new Date(dateToFormat), "GMT", "EEE, MMM d, yyyy");
Logger.log(formattedDate);

Related

Working with Date, Time in Google Apps Script

I need help with some quick coding with google apps script, linking to my googlesheets spreadsheet.
In the googlespreadsheets, I have a cell with the value “26-Jun-2020”. It is a date.
I want to use google apps script to calculate the number of days difference between that date (“26-Jun-2020”) and today’s day, but it won’t do the calculation for me somehow.
If I print only “expiry_date[i]” using Logger.log(expiry_date[i]), it will provide the output “Fri Dec 17 2021 01:00:00 GMT-0500 (Eastern Standard Time) “
function Put_Options_Expiry_Alert() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Long equity (sell puts)");
//var timeZone = AdsApp.currentAccount().getTimeZone(); //Get timezone of current spreadsheet
var status = sheet.getRange("F:F").getValues();
var expiry_date = sheet.getRange("M:M").getValues();
var potential_capitaloutlay_USD = sheet.getRange("Z:Z").getValues();
Logger.log("Length of status = " + status.length);
Logger.log("Length of expiry_date = " + expiry_date.length);
Logger.log("Length of potential_capitaloutlay_USD = " + potential_capitaloutlay_USD.length);
for (var i = 0; i < status.length; i++) {
if (status[i] == "Entered") { //Evaluate if this is a live Put position
//Calculate the time difference of two dates using date2. getTime() – date1. getTime();
//Calculate the no. of days between two dates, divide the time difference of both the dates by no. of milliseconds in a day (1000*60*60*24)
Logger.log("expiry date is = "+expiry_date[i]);
Logger.log("today's date is = "+Date());
var days_to_expiry = dateDiffInDays(expiry_date[i],Date());
Logger.log(days_to_expiry);
}
}
}
// Function that returns the number of days difference between DateA and DateB
// DateA and DateB are javascript Date objects
function dateDiffInDays(DateA, DateB) {
var milliseconds_per_day = 1000 * 24 * 60; // number of milliseconds in a day
const utcA = Date.UTC(2021, DateA.getMonth(), DateA.getDate());
const utcB = Date.UTC(2020, DateB.getMonth(), DateB.getDate());
return Math.floor((utc2 - utc1) / milliseconds_per_day);
}
function timeDiffDays(Start, End) {
var day = 86400000;
var t1 = new Date(Start).valueOf();
var t2 = new Date(End).valueOf();
var d = t2 - t1;
return Math.floor(d / day);
}

Invalid Date in moment.js datetime addition

I want to add time/duration in HH:mm(eg 00:10) to a Date time in format MM-DD-YYYY HH:MM
I have date and time in 2 separate objects so am trying the below
var plannedStartDate = document.getElementById("date1"); //eg 02-12-2020
var plannedStartTime = document.getElementById("plannedStart1"); //eg 09:00
var plannedStartDateTime = moment(plannedStartDate.value + " " + plannedStartTime.value);
var minutes = $("#duration1").text().split(':')[1];
var hours = $("#duration1").text().split(':')[0];
var date = plannedStartDateTime.add(hours, 'hours').add(minutes, 'minutes').format("MM-DD-YYYY HH:mm");
console.log("Final:"+date); //gives invalid date
What am I doing wrong
Check this working sandbox: https://codesandbox.io/s/compassionate-bas-fg1c2
It adds the hours and minutes to the input date and then prints in a given format
var moment = require("moment");
var input = "2020-02-12";
var hoursMinutes = "9:10";
var hours = hoursMinutes.split(":")[0];
var minutes = hoursMinutes.split(":")[1];
var momentInTime = moment(input)
.add(hours, "hours")
.add(minutes, "minutes");
var converted = moment(momentInTime).format("DD-MM-YYYY HH:mm:ss");
console.log(converted);

Dart - Convert time from dd/MM/YYYY to YYYY-MM-dd

How to convert a date from dd/MM/YYYY to YYYY-MM-dd
Example: convert from 08/11/2019 to 2019-11-08
I tried the following code but got the
Invalid date format 08/11/2019 exception
import 'package:intl/intl.dart';
DateFormat('YYYY-MM-dd').format(DateTime.parse('08.11.2019'));
var inputFormat = DateFormat('dd/MM/yyyy');
var date1 = inputFormat.parse('18/08/2019');
var outputFormat = DateFormat('yyyy-MM-dd');
var date2 = outputFormat.format(date1); // 2019-08-18
Or you can use String
var date2String = outputFormat.format(date1); // "2019-08-18"
Try using this package, Jiffy. It is inspired by momentjs.
This can be solved in one line
var dateTime = Jiffy("18/08/2019", "dd/MM/yyyy").format("yyyy-MM-dd"); // 2019-08-18
You can also format it with default formats
var dateTime = Jiffy("18/08/2019", "dd/MM/yyyy").yMMMMd; // August 18, 2019

java.lang.IllegalArgumentException: Invalid format: "Thu May 24 2018 14:00:00 GMT+0200"

I´m trying to convert a String date like "Thu May 24 2018 14:00:00 GMT+0200" to Joda DateTime (v.2.9.9) but I obtain Invalid format exception:
String pattern = "EEE MMM dd yyyy HH:mm:ss 'GMT'Z";
DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern);
for (int i=0; i < arrayHorarios.length; i++) {
DateTime dateTime = new DateTime();
dateTime = formatter.withOffsetParsed().parseDateTime(arrayHorarios[i]);
}
What am I doing wrong? My goal is to convert all Strings containing dates to Java Dates and then save them into DB... what´s the easiest way to do it? (with or without Joda).
EDIT:
I changed to the correct pattern. Using Java DateFormat was useless too:
ObjectMapper mapper = new ObjectMapper();
String[] arrayHorarios = mapper.readValue(horariosSave, String[].class);
DateFormat df = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss z", Locale.ENGLISH);
//sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
List<Date> hor = new ArrayList<Date>();
Date date = new Date();
try {
for (int i=0; i < arrayHorarios.length; i++) {
// conversión de String a Date de los valores
System.out.println("Horario nº:"+i);
System.out.println("String = "+arrayHorarios[i]);
date = df.parse(arrayHorarios[i]);
System.out.println("Date = " + df.format(date));
hor.add(date);
}
System.out.println("Clases guardadas:"+hor.size());
} catch (Exception e) {
e.printStackTrace();
}
This way I get this exception:
java.text.ParseException: Unparseable date: "Fri May 25 2018 12:00:00 GMT+0200"
at java.text.DateFormat.parse(DateFormat.java:366)
java.time
I wonder if there is a way to do it with Java 8 Util Time.
Of course there is.
String pattern = "EEE MMM dd yyyy HH:mm:ss 'GMT'Z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.ENGLISH);
String horario = "Thu May 24 2018 14:00:00 GMT+0200";
OffsetDateTime dateTime = OffsetDateTime.parse(horario, formatter);
System.out.println(dateTime);
Prints:
2018-05-24T14:00+02:00
Imports used are:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
Joda-Time
Not that you’ll regret upgrading to java.time, your Joda-Time code seems to be working too:
String pattern = "EEE MMM dd yyyy HH:mm:ss 'GMT'Z";
DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern);
String horario = "Thu May 24 2018 14:00:00 GMT+0200";
DateTime dateTime = formatter.withOffsetParsed().parseDateTime(horario);
System.out.println(dateTime);
This prints:
2018-05-24T14:00:00.000+02:00
I suspect that your problem may be somewhere else.
PS You may already be aware that the Joda-Time home page says:
Users are now asked to migrate to java.time (JSR-310).
To convert Java Date to Joda DateTime:-
Date date = new Date();
DateTime dateTime = new DateTime(date);
With TimeZone, if required:-
TimeZone timeZone= dateTime.getZone().toTimeZone();
DateTime dateTimeNew = new DateTime(date.getTime(), timeZone);
Date dateTimeZone = dateTime.toDateTimeAtStartOfDay(timeZone).toDate();

TimeZone Example in Flex?

Actually in my Flex Application i'm passing Date(in String format) as well as Timezone(String format) convert into Date type but it is not converting Date type ... it is giving null value and my
sample code like this...
var tzDate:String="20012-12-12";
var tzString:String=tzComboBox.selectedItem;//hear value GMT+0530
var startDate:Date = DateField.stringToDate(tzDate+" "+tzString,"YYYY-MM-DD TZD");
Alert.show(startDate);//hear value giving "Null"
The problem is it's not converting Date format...Plz Help me
use parse function and format date before parsing
var tzDate:String="2012-12-12";
var tzString:String="GMT+0530";
var dateformat:DateFormatter = new DateFormatter();
dateformat.formatString = "YYYY/MM/DD";
var dateStr:String = dateformat.format(tzDate) +" "+ tzString;
//dateStr is 2012/12/12 GMT+0530
var startDate:Date = new Date(Date.parse(dateStr));
Alert.show(startDate.toString());
//Show Date of Local time Zone
//Tue Dec 11 21:30:00 GMT+0300 2012
Hopes that Helps

Resources