Is there an easier way to write this method? - javascript

Hello everybody reading this.
I have a method to get todays date with current time.
If the deadline value in database is null it will get current datetime and formats it to the right format. else it will just format the deadline.
But I was wondering if there is an easier way to do this?
formatDateTime(deadline){
var DateTime;
if(deadline == null){
var myDate = new Date();
var month = ('0' + (myDate.getMonth() + 1)).slice(-2);
var date = ('0' + myDate.getDate()).slice(-2);
var year = myDate.getFullYear();
var hour = ('0' + myDate.getHours()).slice(-2);
var minute = ('0' + myDate.getMinutes()).slice(-2);
var formattedDate = year + '-' + month + '-' + date + 'T' + hour + ':' + minute;
DateTime = moment(formattedDate, 'YYYY-MM-DD HH:mm').format('YYYY-MM-DDTHH:mm');
} else {
DateTime = moment(deadline, 'YYYY-MM-DD HH:mm').format('YYYY-MM-DDTHH:mm');
};
return DateTime;
}

As #Andrew said, You are already using moment
So this version will do exactly what your current function do
function formatDateTime(deadline){
if(deadline == null){
deadline = moment().format('YYYY-MM-DD HH:mm');
}
return moment(deadline, 'YYYY-MM-DD HH:mm').format('YYYY-MM-DDTHH:mm');
}

if you're using momentjs, you can just pass a Date object to the moment function. if the function receives no arguments, it will default to the current time (same as new Date()).
formatDateTime(deadline) {
return moment(deadline).format('YYYY-MM-DDTHH:mm');
}

Related

Javascript n months after today

I am trying to get the day 90 days after today. This is my code:
var today = new Date();
var threeMonthsFromToday = new Date(today.setDate(today.getDate() + 90));
When I print threeMonthsFromToday, I get the correct date: 2017-04-24T15:17:42.641Z. However, when I try to reformat the date to be in the form dd/mm/yyyy using this code:
var day = ('0' + threeMonthsFromToday.getDate()).slice(-2);
var month = ('0' + threeMonthsFromToday.getMonth() + 1).slice(-2);
var year = threeMonthsFromToday.getFullYear();
var date = day + '/' + month + '/' + year;
I get a completely different and invalid date: 24/31/2017.
I have been debugging this for hours and still can't seem to figure what I am doing wrong.
Well, '0' + threeMonthsFromToday.getMonth() give you a string : "03" then you add 1 converted to string giving you "031" for month before slice.
Use this :
var month = ('0' + (threeMonthsFromToday.getMonth() + 1)).slice(-2);
You are missing the basic BODMAS rule here please modify your code as follows
var today = new Date();
var threeMonthsFromToday = new Date(today.setDate(today.getDate() + 90));
var day = ('0' + threeMonthsFromToday.getDate()).slice(-2);
var month = ('0' + (threeMonthsFromToday.getMonth() + 1)).slice(-2);
var year = threeMonthsFromToday.getFullYear();
var date = day + '/' + month + '/' + year;
the operations are performed from left to right, so month is getting converted to string before being added to a number. Including a bracket will first perform operation inside bracket and then make it a string
Can you use toLocaleString?
threeMonthsFromToday.toLocaleDateString('en-GB')
Below does the trick for you ...
getMonth() +1 before adding the "0" to it so that you get an arithematic +1
var today = new Date();
var threeMonthsFromToday = new Date(today.setDate(today.getDate() + 90));
var day = ('0' + threeMonthsFromToday.getDate()).slice(-2);
var month = ('0' + (threeMonthsFromToday.getMonth()+1)).slice(-2);
var year = threeMonthsFromToday.getFullYear();
var date = day + '/' + month + '/' + year;
console.log(date);
This should work.
var day = threeMonthsFromToday.getDate()
if(day < 10){
day = '0' + day
}
var month = threeMonthsFromToday.getMonth()+1
if(month<10){
month = '0' + month
}
var year = threeMonthsFromToday.getFullYear()
var date = day + '/' + month + '/' + year
Use Simple toLocaleDateString method
The toLocaleDateString() method returns a string with a language sensitive representation of the date portion of this date.
var today = new Date();
var threeMonthsFromToday = new Date(today.setDate(today.getDate() + 90));
var date = threeMonthsFromToday.toLocaleDateString();
console.log(date);
//result in console : "24/04/2017"
Try it out on your console.

How do I get a date in YYYY-MM-DD format?

Normally if I wanted to get the date I could just do something like
var d = new Date();
console.log(d);
The problem with doing that, is when I run that code, it returns:
Mon Aug 24 2015 4:20:00 GMT-0800 (Pacific Standard Time)
How could I get the Date() method to return a value in a "MM-DD-YYYY" format so it would return something like:
8/24/2015
Or, maybe MM-DD-YYYY H:M
8/24/2016 4:20
Just use the built-in .toISOString() method like so: toISOString().split('T')[0]. Simple, clean and all in a single line.
var date = (new Date()).toISOString().split('T')[0];
document.getElementById('date').innerHTML = date;
<div id="date"></div>
Please note that the timezone of the formatted string is UTC rather than local time.
The below code is a way of doing it. If you have a date, pass it to the convertDate() function and it will return a string in the YYYY-MM-DD format:
var todaysDate = new Date();
function convertDate(date) {
var yyyy = date.getFullYear().toString();
var mm = (date.getMonth()+1).toString();
var dd = date.getDate().toString();
var mmChars = mm.split('');
var ddChars = dd.split('');
return yyyy + '-' + (mmChars[1]?mm:"0"+mmChars[0]) + '-' + (ddChars[1]?dd:"0"+ddChars[0]);
}
console.log(convertDate(todaysDate)); // Returns: 2015-08-25
Yet another way:
var today = new Date().getFullYear()+'-'+("0"+(new Date().getMonth()+1)).slice(-2)+'-'+("0"+new Date().getDate()).slice(-2)
document.getElementById("today").innerHTML = today
<div id="today">
By using Moment.js library, you can do:
var datetime = new Date("2015-09-17 15:00:00");
datetime = moment(datetime).format("YYYY-MM-DD");
var today = new Date();
function formatDate(date) {
var dd = date.getDate();
var mm = date.getMonth() + 1; //January is 0!
var yyyy = date.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
//return dd + '/' + mm + '/' + yyyy;
return yyyy + '/' + mm + '/' +dd ;
}
console.log(formatDate(today));
function formatdate(userDate){
var omar= new Date(userDate);
y = omar.getFullYear().toString();
m = omar.getMonth().toString();
d = omar.getDate().toString();
omar=y+m+d;
return omar;
}
console.log(formatDate("12/31/2014"));
What you want to achieve can be accomplished with native JavaScript. The object Date has methods that generate exactly the output you wish.
Here are code examples:
var d = new Date();
console.log(d);
>>> Sun Jan 28 2018 08:28:04 GMT+0000 (GMT)
console.log(d.toLocaleDateString());
>>> 1/28/2018
console.log(d.toLocaleString());
>>> 1/28/2018, 8:28:04 AM
There is really no need to reinvent the wheel.
If you are trying to get the 'local-ISO' date string. Try the code below.
function (date) {
return new Date(+date - date.getTimezoneOffset() * 60 * 1000).toISOString().split(/[TZ]/).slice(0, 2).join(' ');
}
+date Get milliseconds from a date.
Ref: Date.prototype.getTimezoneOffset
Have fun with it :)
Here is a simple function I created when once I kept working on a project where I constantly needed to get today, yesterday, and tomorrow's date in this format.
function returnYYYYMMDD(numFromToday = 0){
let d = new Date();
d.setDate(d.getDate() + numFromToday);
const month = d.getMonth() < 9 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1;
const day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate();
return `${d.getFullYear()}-${month}-${day}`;
}
console.log(returnYYYYMMDD(-1)); // returns yesterday
console.log(returnYYYYMMDD()); // returns today
console.log(returnYYYYMMDD(1)); // returns tomorrow
Can easily be modified to pass it a date instead, but here you pass a number and it will return that many days from today.
If you're not opposed to adding a small library, Date-Mirror (NPM or unpkg) allows you to format an existing date in YYYY-MM-DD into whatever date string format you'd like.
date('n/j/Y', '2020-02-07') // 2/7/2020
date('n/j/Y g:iA', '2020-02-07 4:45PM') // 2/7/2020 4:45PM
date('n/j [until] n/j', '2020-02-07', '2020-02-08') // 2/7 until 2/8
Disclaimer: I developed Date-Mirror.
This will convert a unix timestamp to local date (+ time)
function UnixTimeToLocalDate = function( unix_epoch_time )
{
var date,
str;
date = new Date( unix_epoch_time * 1000 );
str = date.getFullYear() + '-' +
(date.getMonth() + 1 + '').padStart( 2, '0' ) + '-' +
(date.getDate() + '').padStart( 2, '0' );
// If you need hh:mm:ss too then
str += ' ' +
(date.getHours() + '').padStart( 2, '0' ) + ':' +
(date.getMinutes() + '').padStart( 2, '0' ) + ':' +
(date.getSeconds() + '').padStart( 2, '0' );
return str;
}
If you want a text format that's good for sorting use:
function formatDateYYYYMMDDHHMMSS(date){
// YYYY-MM-DD HH:MM:SS
const datePart = date.toISOString().split("T")[0]
const timePart = date.toLocaleString('en-US', {hour12: false}).split(",")[1]
return datePart + timePart
}
As prototype:
Date.prototype.toSortString = function(){
const date = new Date(this.valueOf());
return date.toISOString().split("T")[0] +
date.toLocaleString('en-US', {hour12: false}).split(",")[1]
}
Simple one line elegant solution for fullYear-fullMonth-FullDay as '2000-01-01'
new Date().toLocaleDateString("fr-CA",
{year:"numeric", month: "2-digit", day:"2-digit"}
)
const padTo2Digits = num => {
return num.toString().padStart(2, '0')
}
const formatDate = date => {
return [
date.getFullYear(),
padTo2Digits(date.getMonth() + 1),
padTo2Digits(date.getDate())
].join('-')
}
let value = formatDate(new Date())
document.getElementById('dayFormatUS').innerHTML = value
const transformDate = date => {
const convert = date.split('-').reverse()
return convert.join('/')
}
document.getElementById('dayFormatBR').innerHTML = transformDate(value)
<div>
Format US -
<span id='dayFormatUS'></span>
</div>
<div>
Format BR -
<span id='dayFormatBR'></span>
</div>

Date and time in javascript

How can I get the date and time in javascript as 12/08/2015-1:49? I tried the following but I get an error TypeError: now.format is not a function
var now = new Date();
now.format("dd/mm/yy-h:mm tt");
console.log(now); //TypeError: now.format is not a function
There is no any format method for Date in JavaScript. Either you need to use any other external libraries like momentjs, or write your own script to format.
Here is example how you can convert date to dd/mm/yy-h:mm tt format
var now = new Date();
var date = now.getDate() + "/" + (now.getMonth() + 1) + "/" + now.getFullYear() + "-" + now.getHours() + ":" + now.getMinutes() + " " + (now.getHours() > 12 ? "PM" : "AM");
console.log(date)
Try this:
function getFormattedDate() {
var date = new Date();
var str = date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getYear() + "-" + date.getHours() + ":" + date.getMinutes() + " " + date.getSeconds();
return str;
}
Extend Date`s prototype, add function format
Date.prototype.format = function(format){
format = format || "Y/M/D H:I:S";
var data = {
y: this.getFullYear() % 100,
Y: this.getFullYear(),
m: this.getMonth() + 1,
d: this.getDate(),
h: this.getHours(),
i: this.getMinutes(),
s: this.getSeconds()
};
var needAddZeroLTTen = "mdhis".split('');
for(var i = 0; i < needAddZeroLTTen.length; i ++){
var prop = needAddZeroLTTen[i];
data[prop.toUpperCase()] = data[prop] < 10 ? ('0' + data[prop]) : data[prop];
}
var dateStr = format;
for(var i in data){
var reg = new RegExp(i,'g');
dateStr = dateStr.replace(reg, data[i]);
}
return dateStr;
}
Then use below code to format a date
var date = new Date();
var dateStr = date.format('D/M/y-h:I');
the best way to manage dates in js is using http://momentjs.com/ here you will find a great way to format the dates
You can either
do this by hand by using the functions on Date like date.getMonth(), however these do not support zero padding, and it gets quite fiddly. Only do this if you cannot include a third-party library, you're obsessive about load time / performance or you really enjoy re-inventing the wheel.
Use a third-party library like moment, this has multiple formats and supports padding, e.g. MM will force month as two characters.
Example
var now = new Date();
console.log(moment(now).format("DD/MM/YY-hh:mm Z"));
Moment.JS would help you.
Please take a look on this JSFiddle: http://jsfiddle.net/f3zp5zuv/
alert (moment('2015 Apr 30').format('DD/MM/YY -h:mm'))
Moment: http://momentjs.com/docs/#/displaying/
alert (moment('2015 Apr 30 14:42:00').format('DD/MM/YY -h:mm'))
<script src="http://momentjs.com/downloads/moment.js"></script>

How do I convert timezone date to correct local date?

I have this date:
2015-05-28T23:00:00.000Z
I need to convert it to the local date which would be (in this format):
29/05/2015
I would expect the above formatted date to be correct based on the date string above.
How would I do this?
Thank you
convert it to Date object:
var dateString = '2015-05-28T23:00:00.000Z';
var date = new Date(dateString)
then you cant format it:
var formatedDate = date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
But you can also use moment.js
moment(dateString).format('DD/MM/YYYY');
It's been well covered elsewhere that using the Date constructor to parse strings isn't a good idea. The format in the OP is consistent with ES5 and will be parsed correctly by modern browsers, but not IE 8 which still has a significant user share.
Parsing the string manually isn't difficult:
function isoStringToDate(s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0], --b[1], b[2], b[3], b[4], b[5], b[6]));
}
Then to format it:
function dateToDMY(d) {
function z(n){return (n<10?'0':'') + n}
return z(d.getDate()) + '/' + z(d.getMonth()+1) + '/' + d.getFullYear();
}
console.log(dateToDMY(isoStringToDate('2015-05-28T23:00:00.000Z'))); // 29/05/2015
To be consistent with ES5, the parse function should check values aren't out of range but if you're confident of the correctness of the string that shouldn't be necessary.
Thank you for your replies.
I've got it formatted by doing:
var d = new Date('2015-05-28T23:00:00.000Z');
var n = d.getDate() + '/' + (d.getMonth() +1 ) + '/' + d.getFullYear();
document.getElementById("demo").innerHTML = n;
Please add the following code in script
<script>
var d = new Date("2015-05-28T23:00:00.000Z");
var str=d.toString();
var date = new Date(str),
mnth = ("0" + (date.getMonth()+1)).slice(-2),
day = ("0" + date.getDate()).slice(-2);
var local_date=[ date.getFullYear(), mnth, day ].join("/"); //yyyy/mm/dd
</script>
Hope it works.Thank you

Daylight saving issues with get date function

I am having issues with day light savings, I have tried tons of diferent ways but not working. Our clients are global so I did not want to use any timezone stuff.
The idea is you give a date and amount of days and get back a date. the date input has to be "DD-MM-YYYY" as we get this from an other system.
this is the code
CallculateDateFromDays = function(startDate, days) {
var policy_start_date_array = startDate.split("-");
var policy_start_date = new Date(policy_start_date_array[2], policy_start_date_array[1]-1, policy_start_date_array[0]);
var epoch = Math.floor(policy_start_date.getTime()/1000);
var days_seconds = (days - 1) * 86400;
var total_seconds = epoch + days_seconds;
var end_date = new Date(total_seconds*1000);
var dateString = ("0" + (end_date.getDate())).slice(-2) + "-" + ("0" + (end_date.getMonth()+1)).slice(-2) + "-" + end_date.getFullYear();
alert(dateString + " " + epoch);
};
CallculateDateFromDays("27-10-2013",2);
this should return the 28-10-2013 but when I use the date "27-10-2013" it returns "27-10-2013", but any other date is fine. I have tried using UTC but still same result.
Any ideas
Thanks

Categories