Check different date formats - javascript

I have function:
sample(date){
//operations, for example add one week (7 days)
return date;
}
var one = new Date('2012-07-16');
var two = new Date('07/16/2012');
var new = sample(one); // or sample(two)
var day = new.getDate();
var month = new.getMonth();
var year = new.gerYear();
alert(day + month + year);
and now i would like show this date, but how can i check format this date?
For example:
alert(sample(one));
should show me date with format 2012-07-23
and if
alert(sample(one));
should show me 07/23/2012
but how can i check format current date? is this possible?

Date objects don't "remember" the format with which they were created - they're just a wrapper for the standard Javascript "milliseconds since the epoch" time values.
You'll need to either roll your own "date to string" functions, or use one of the popular existing libraries (e.g. Datejs)

Related

Convert string to date and alter that date

Good day, I am generating 3 dates from a string, I hope the output was:
billing date: 2020/01/11
cutoff start: 2019/11/11
cuttof end: 2019/12/10
but I get the following:
billing date: 2020/11/10
cutoff start: 2019/11/10
cuttof end: 2019/12/10
I would like to know how javascript works with variables or what is the problem since everything is altered
var month = "Jan-20"
var coverage_month_obj = moment(month, 'MMM-YY').toDate();
var billing_date = new Date(coverage_month_obj.setDate(coverage_month_obj.getDate() + 10))
var cutoff_end = new Date(billing_date.setMonth(billing_date.getMonth() - 1))
cutoff_end = new Date(billing_date.setDate(billing_date.getDate() - 1))
var cutoff_start = new Date(billing_date.setMonth(billing_date.getMonth() - 1))
I would like to know how javascript works with variables or what is the problem since everything is altered
Put simply, calling setXXX on a javascript date variable updates that variable in place. ie, it is what we would call "mutable". You might have assumed dates were immutable and did not change in place.
To answer on a better way to achieve your goal, I'd suggest using the other functionality of momentjs to calculate your 3 dates from the given input string.
var month = "Jan-20"
var coverage_month = moment(month, 'MMM-YY');
//Jan-20 I need to convert it into date format and that the day is 11 (2020/01/11) cutoff start, are two months less from that date (2020/11/11) and cutoff end is one month less from Jan-20, but ends on day 10 (2020/12/10)
var billing_date = coverage_month.clone().add(10, 'days');
var cutoff_start = billing_date.clone().subtract(2, 'months');
var cutoff_end = billing_date.clone().subtract(1,'months').subtract(1,'day')
console.log("billing_date",billing_date);
console.log('cutoff_start',cutoff_start);
console.log('cutoff_end',cutoff_end);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Add 1 day to date from spreadsheet via Google App Script / Javascript- Month Keeps Reseting to current month

I am trying to set up a Google App Script function that grabs a date (formatted dd/mm/yy) from the last column of a spread, and creates a new column with the date + one day.
I have seen previous solutions and tried to use the same, i.e.newDate.setDate(lastDate.getDate()+1) but have had issues getting the value formatted correctly in the script. This is a variation of my code that I'm using to loop through for a year's worth of values to see what I get:
for (var i=0;i<365;i++){
var lastRow = outputSheet.getLastRow();
var newDate = new Date();
var lastDate = outputSheet.getRange(lastRow,1).getValue();
var newDateRng = outputSheet.getRange(lastRow+1,1);
Logger.log(lastDate + 1, typeof lastDate, typeof (lastDate + 1));
newDate.setDate(lastDate.getDate());
Logger.log(newDate);
newDate.setDate((newDate.getDate() + 1));
Logger.log(newDate);
var newDateFormatted = Utilities.formatDate(newDate, ss.getSpreadsheetTimeZone(), "dd/MM/YY");
Logger.log(newDateFormatted);
newDateRng.setValue(newDateFormatted);
}
With a start date of "01/03/2020", I get the following behaviour:
01/03/2020
02/05/2020
03/05/2020
...
31/05/2020
01/06/2020
02/05/2020
03/05/2020
...
31/05/2020
01/06/2020
02/05/2020
...
etc. All the way through the year. Although the day increase, the month seems to reset after the first day of the month.
As a note, I am specifically looking to pick the date off of the spreadsheet rather than using new Date as today and new Date +1 as tomorrow.
Thanks
You need to use a different variable in the loop otherwise you will always return to the same month.
Also avoid using strings for the result, keep date objects and display it properly.
The code goes like this :
function otherTest(){
var lastDate = SpreadsheetApp.getActiveSheet().getActiveCell().getValue();
var date = new Date(lastDate); // create new date object
var result = [];
for (var i=0;i<365;i++){
date=new Date(date).setDate(new Date(date).getDate()+1)
Logger.log('date='+new Date(date))
result.push([new Date(date)]);
}
SpreadsheetApp.getActiveSheet().getRange(1,2,result.length,1).setValues(result).setNumberFormat('dd/MM/yyyy');
}

Convert specific date in Javascript [duplicate]

This question already has answers here:
Parse DateTime string in JavaScript
(9 answers)
Closed 5 years ago.
I have problem with convert date which I get from API. Format is for example "16/09/25"
I try do it like this
var x = new Date(dateFromApi)
and console thorw me error.
Parsing a date string is very simple. A function that will work in any host from IE 4 onward is:
function parseDMY(s) {
var b = s.split(/\D/);
return new Date(b[2], b[1]-1, b[0]);
}
console.log(parseDMY('16/09/25'));
Where the year is >= 0 or <= 99, 1900 is added so 25 becomes 1925. Preserving years in this range (so 25 is 0025) requires an additional line of code.
It is safest to provide the Date constructor with the individual parts of the date (i.e., year, month and day of the month).
In ES6 you can provide those elements like this:
var x = new Date(...dateFromApi.split('/').reverse().map( (p,i) => p-(i%2) ));
The map is needed to subtract one from the month number, as it should be zero-based in numeric format.
Note the new Date(year, month, day) version of the constructor will assume 19xx when you provide only 2 digits.
var dateFromApi = "16/09/25"
var x = new Date(...dateFromApi.split('/').reverse().map( (p,i) => p-(i%2) ));
console.log(x.toDateString());
In ES5, it would be a bit longer, like this:
new (Date.bind.apply(Date, (dateFromApi+'/').split('/').reverse()
.map(function (p,i) { return p-(i==2); })));
var dateFromApi = "16/09/25"
var x = new (Date.bind.apply(Date, (dateFromApi+'/').split('/').reverse()
.map(function (p,i) { return p-(i==2); })));
console.log(x.toDateString());
Of course, this assumes that the input format is consistently in the order DD/MM/YY (or D/MM/YYYY, as long as the order is the same); that valid dates are passed, and that you accept how 2-digit years are mapped to 4-digit years.
Your format is DD/MM/YY and it is not accepted by Date and will throw an error.
This is because, as mentioned by #MattJohnson, the accepted Date formats vary by locale and the only official format is YYYY-MM-DD (which is derived from ISO date string. Read here).
In most cases, Date will accept the format YY-MM-DD. So we can simply do this:
var date = "16/09/25"; // date received from API
var split_date = date.split('/'); // outputs ["16","09",""25"]
var rearranged_date = [split_date[1], split_date[0], split_date[2]].join('/'); // outputs "09/16/25"
var proper_date = new Date(rearranged_date);
In other cases, it is best to provide the full-year YYYY instead of just YY.

Extract Month and Day in Javascript

I have the date in this format: 1347564203.713372
And need to end up with 2 variables, one that is the month from that date and another that is the day from that date.
How do I do this using Javascript/jQuery?
This should do:
var myDate = 1347564203.713372;
var d= new Date(myDate*1000);
var month = d.getMonth();
var day = d.getDate();
Create a Date object, use setTime to put your timestamp in there, then get the relevant parts:
var d = new Date(), t = 1347564203.713372;
d.setTime(t*1000); // JS uses timestamps in milliseconds
alert(d.getUTCDate());
alert(["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][d.getUTCMonth()]);
Note use of getUTC* functions - this helps avoid timezone issues and DST.

How can I make Datejs return only the year when only the year is given?

I'm using Datjs to take a date from a user and convert it to a format suitable for storage in my database. When I supply a date with month, day, and year, I get just what I want, the date formatted year-month-day:
var d1 = Date.parse('02/22/1984');
console.log(d1.toString('yyyy-MM-dd')); //Prints '1984-02-22'
However, when I give a year only, I get back the same year, followed by today's month and day:
var d1 = Date.parse('1984');
console.log(d1.toString('yyyy-MM-dd')); //Prints '1984-12-19'
What can I do to ensure that when the user types in nothing but a year that just that year is returned in the following format
1984-00-00
Likewise, if only the month and year are give I'd like it formatted like this:
1984-02-00
Datejs returns a JavaScript Date object. This object is intended to represent a point in time and a point in time necessarily includes the month and day. When not provided, Datejs defaults these values to the current month and day. If you don't want to display that information, then change your formatting pattern:
var d1 = Date.parse('1984');
console.log(d1.toString('yyyy')); // prints 1984
If you need to change the pattern based on what the user originally entered, then you need to save that information, so that you know what to print later.
A simple example follows:
function DatePrinter(input) {
var s = input.split("/").length;
this.fmt = ["dd", "MM", "yyyy"].slice(3 - s).reverse().join("-");
this.date = Date.parse(input);
}
DatePrinter.prototype.toString = function() {
return (this.date.toString(this.fmt) + "-00-00").slice(0, 10);
}
Some tests:
new DatePrinter("02/22/1984").toString() // "1984-02-22"
new DatePrinter("02/1984").toString() // "1984-02-00"
new DatePrinter("1984").toString() // "1984-00-00"

Categories

Resources