Convert Date string to Object with current timezone format [duplicate] - javascript

This question already has answers here:
How to convert dd/mm/yyyy string into JavaScript Date object? [duplicate]
(10 answers)
Closed 2 years ago.
I have this code to add a reminder to a calendar
function addCalendarEvent(eventDate, eventTitle){
let dateObj = new Date(eventDate);
let calendarId = "me#gmail.com";
let cal = CalendarApp.getCalendarById(calendarId);
let event = cal.createAllDayEvent(eventTitle, dateObj)
event.addEmailReminder(420)
}
The eventDate is passed into the function as a string in the format dd/MM/YYYY but the output from let dateObj = new Date(eventDate); is in american format. ie. 02/10/2020 comes out as Mon Feb 10 2020 00:00:00 GMT+0000 (Greenwich Mean Time). Any help correcting this would be great. Dates give me an absolute headache

In the end I decided that just working with date objects from the off would be easiest

This will give you the date object of the string in the format dd/MM/YYYY
function ddmmyyyytFormatterWithTime(date) {
var dateDiv = date.split('/');
var date = new Date();
date.setDate(dateDiv[0]);
date.setMonth(--dateDiv[1]); // -- since it starts from 0
date.setFullYear(dateDiv[2]--);
return date;
};
function ddmmyyyytFormatter(date) {
var dateDiv = date.split('/');
var date = new Date();
date.setHours(0, 0, 0, 0); // to reset time
date.setDate(dateDiv[0]);
date.setMonth(--dateDiv[1]); // -- since it starts from 0
date.setFullYear(dateDiv[2]);
return date;
};
var date = ddmmyyyytFormatter("10/02/2020");
var dateWithTime = ddmmyyyytFormatterWithTime("10/02/2020");

Related

Why 1 day off when I try to convert date into toisostring in javascript?

I am trying to convert date object to ISOString() formate. But it return me 1 day off ( I mean it reduce 1 day ).
var fromDate = {
day:4,
month:5,
year:2012
}
var fromDateString = new Date(fromDate.year+'-'+fromDate.month+'-'+fromDate.day)
console.log(fromDateString.toISOString())
It is because of timezone, new Date() is in your current timezone, toISOString() is using standard timezone.
I have searched and I find best solution for every date object to convert in any format.
Comment if you agree?
var dateObj = {
day:2,
month:5,
year:2012
}
var date = new Date;
date.setFullYear(dateObj.year,dateObj.month-1,dateObj.day)
console.log(date)

new Date() always read dd/mm/yyyy as mm/dd/yyyy(month first) hence day and month values get mixed resulting in NaN/Error [duplicate]

This question already has answers here:
How to convert dd/mm/yyyy string into JavaScript Date object? [duplicate]
(10 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 3 years ago.
When converting date for example:
var dateObj = new Date("10/01/2019");
console.log(dateObj);
returns Tue Oct 01 2019 00:00:00 i.e. it takes in the day as month and likewise with the month value
How to make new Date() to take dd/mm/yyyy ??
Answer is here: https://stackoverflow.com/a/33299764/6664779
(From original answer) We can use split function and then join up the parts to create a new date object:
var dateString = "23/10/2019"; // Oct 23
var dateParts = dateString.split("/");
// month is 0-based, that's why we need dataParts[1] - 1
var dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]);
document.body.innerHTML = dateObject.toString();

Javascript convert date string to object [duplicate]

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
I'm trying to convert a date in string format to a Date object in JavaScript. The date is coming from the openweathermap.org API, which gives the date string in the following format:
'2018-04-28 09:00:00' or 'yyyy-mm-dd hh:mm:ss'
I know that the JavaScript Date class can take other string formats of dates, but this one returns NaN when I try anything with it. How can I convert a date string, like the one above, and convert it easily to a JavaScript object? Thanks!
Since you are getting NaN while directly converting the string to date. You can split the string on spaces, - and : and then pass the value to date constructor and generate the date object.
const str = `2018-04-28 09:00:00`;
const [date, time] = str.split(' ');
const [year, month, day] = date.split('-');
const [hh, mm, sec] = time.split(':');
const dateObj = new Date(year, month - 1, day, hh, mm, sec);
console.log(dateObj);
As pointed out by #RobG, this could also be done using the regex.
const str = `2018-04-28 09:00:00`;
var b = str.split(/\D/);
var date = new Date(b[0],b[1]-1,b[2],b[3],b[4],b[5]);
console.log(date);
const str = `2018-04-28 09:00:00`,
date = new Date(...(str.split(/\D/).map((v,i)=>i==1?--v:v)));
console.log(date);
Just try new Date(str)
d = new Date("2018-04-20 09:00:00")
Fri Apr 20 2018 09:00:00 GMT+0800 (Hong Kong Standard Time)
d.getDate()
20
ref: https://www.ecma-international.org/ecma-262/6.0/#sec-date-time-string-format

Add Number of months to a Date in a text field

function addDays(){
var myDate =document.getElementById('treatdate');
var numberOfDaysToAdd = document.getElementById('resultdays');
var tset = numberOfDaysToAdd.value;
var result1 = myDate.value.addMonths(parseInt(tset));
var pldate= moment(result1).format('YYYY-MM-DD');
return pldate; }
'treatdate' is an id for a treatment date which is pulled from my database. Thanks in advance.
You can always use moment.js library for Date manipulations. http://momentjs.com/
For your problem you can do the following.
function addDays(){
var datefrmDb = $('#treatdate').val();
var monthstoadd= $('#resultdays').val();
var new_date = (moment(datefrmDb, "YYYY-MM-DD").add('months', monthstoadd)).format("YYYY-MM-DD");
return new_date;
}
If your date format is yyyy-MM-dd
var myDate = new Date(document.getElementById('treatdate').value);
this will a date and time.
Example:
var dd = new Date("2014-02-02 11:11:11")
console log
Sun Feb 02 2014 11:11:11 GMT+0000 (GMT Standard Time)
See if this snippet can help you understand how to manipulate dates. To change/add the months to a Date() object you can use the setMonth() method.
numberOfMonthsToAdd = 5; // the number of months that you want to add
date = new Date(); // creating a Date object
date.setMonth(numberOfMonthsToAdd); // adding the number of months
Note that you may add numbers beyond 12 - the object handles the date, and jumps to the next year.

UK Date issue in java script date object [duplicate]

This question already has answers here:
JavaScript date objects UK dates
(6 answers)
Closed 9 years ago.
I have the below code. If we try to retrieve the day, month and year in UK server setup. The date object returns an incorrect value.
var startDate = "30/08/2013";
var d = new Date(startDate);
alert(d.getFullYear()); //2015
Please help me
Use moment.js if you want better control of parsing:
var startDate = "30/08/2013";
var m = moment(startDate,"DD/MM/YYYY");
alert(m.year()); //2013
Try passing the date as a list of arguments instead:
var startDate = "30/08/2013"; // Would also work with 30-08-2013
var startDateArray;
if(startDate.contains('/'))
startDateArray = startDate.split('/');
else if (startDate.contains('-'))
startDateArray = startDate.split('-');
else if (startDate.contains('.'))
startDateArray = startDate.split('.');
var d = new Date(startDateArray[2], startDateArray[1]-1, startDateArray[0]); // Month is 0 based, that's why we are subtracting 1

Categories

Resources