Convert date to ccyymmdd using javascript - javascript

I need to use JavaScript to covert a date to to from '2012-09-15T00:00:00' to a CCYYMMDD format? How can I do this?

I don't see what .NET and XSLT have to do with your question.
You could use the Date constructor to parse the ISO 8601 encoded string into a javascript Date object:
var dateStr = '2012-09-15T00:00:00';
var date = new Date(dateStr);
and then build the desired format:
var year = '' + date.getFullYear();
var month = date.getMonth() + 1;
month = month < 10 ? '0' + month : month;
var day = '' + date.getDate();
day = day < 10 ? '0' + day : day;
var formattedDate = year + month + day;
And here's a live demo.

Using replace and split.
var date = '2012-09-15T00:00:00';
date = date.replace(/-/,"").split("T")[0];// date will be 20120915

Related

How to convert a date formatted (YYMMDD) as string but with 00 days?

I have a date formatted as string, eg: 240800. The date format for that string is YYMMDD. With the below code, I can convert the string to date but it doesn't always work in deducting 1 day. I need my output to be a valid date, not with 00 day. So with the date above, it should be converted and formatted to 07/31/2024.
Here's what I got so far.
function formatDate(stringDate) {
var year = stringDate.substring(0,2);
var month = stringDate.substring(2,4);
var day = stringDate.substring(4,6);
var date = new Date('20' + year, month, day);
var formattedDate = date.getMonth() + '/' + date.getDate() + '/' + date.getFullYear();
console.log(formattedDate);
}
Working:
"240800" = 7/31/2024
All months from 4 to 12
Not Working:
"240100" = 0/31/2024 x
"240200" = 1/29/2024 x
"240300" = 2/31/2024 x
The reason is the date variable parameter in new Date() is counted as 0~11, not the general range,1~12.
So the working answer actually is wrong. It seems like being right just for July and August have 31 days.
The correct way is to firstly deduct 1 month and then calculate it. After all of the process is done, you can add 1 month in the end.
The below is working codes:
function formatDate(stringDate) {
var year = stringDate.substring(0,2);
//deduct 1 month firstly
var month = Number(stringDate.substring(2,4))-1;
var day = stringDate.substring(4,6);
var date = new Date('20' + year, month, day);
//add 1 month finally
var formattedDate = date.getMonth()+1 + '/' + date.getDate() + '/' + date.getFullYear();
console.log(formattedDate);
}
formatDate('240100');
In python Assuming your string is yymmdd below function should do what you want. I am sure javascript has some module for date handling.
from datetime import datetime, timedelta
def fd(s):
d=datetime.strptime(s[:-2],'%y%m')+timedelta(days=int(s[-2:])-1)
return d.strftime('%m/%d/%Y')
Try this ..
function formatDate(stringDate) {
var year = stringDate.substring(0,2);
var month = stringDate.substring(2,4);
var day = stringDate.substring(4,6);
var d1;
if (day==="00")
{
d1 = new Date(month + '/01/20' + year);
d1.setDate(d1.getDate() -1);
//console.log("day1" + d1);
}
else
{
d1 = new Date('20' + year, month, day);
}
var formattedDate = d1.getMonth() + '/' + d1.getDate() + '/' + d1.getFullYear();
console.log(formattedDate);
}

How to get tomorrow's date of a specific date

I am trying to get tomorrow's date of a specific date using JavaScript in format (yyyy-mm-dd). For example the specific date is 2021-08-31 and I have got this script:
var date = "2021-08-31"
date = new Date(date.split("-")[0],date.split("-")[1],date.split("-")[2])
date.setDate(date.getDate() + 1);
var tomorrows_date_month = date.getMonth()
var tomorrows_date_day = date.getDate()
var tomorrows_date_year = date.getFullYear()
console.log(tomorrows_date_year + "-" + tomorrows_date_month + "-" + tomorrows_date_day)
The expected output is:
2021-09-01
But the output of this code is :
2021-9-2
First you don't need split "2021-08-31" to use as date parameter, so just use new Date("2021-08-31");
Second note that you need to use d.getMonth() + 1 and add leading zero if the length is less than 2:
Try this one:
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
var date = "2021-08-31"
var date1 = new Date(date);
console.log(formatDate(date1.addDays(1)));
Internally js month is stored as a value between 0 and 11. So you need to minusdate.split("-")[1] by 1. Otherwise, javascript will think that your month is actually September and we know that "2021-09-32" is translated to "2021-10-2", therefore the date is shown as "2".
var date = "2021-08-31"
date = new Date(date.split("-")[0],date.split("-")[1] - 1,date.split("-")[2])
date.setDate(date.getDate() + 1)
var tomorrows_date_month = date.getMonth() + 1
var tomorrows_date_day = date.getDate()
var tomorrows_date_year = date.getFullYear()
console.log(tomorrows_date_year + "-" + tomorrows_date_month + "-" + tomorrows_date_day)
Also note that date = new Date("2021-08-31") is enough for converting a string into a Date object.
new Date(new Date(date + 'T00:00Z').getTime() + 86400000).toISOString().substr(0, 10)
The added 'T00:00Z' assures the date is parsed as UTC, to match the UTC timezone used by toISOString(). Adding 86400000 (the number of milliseconds in one day) advances the date without having to fuss with the date field directly.

Javascript datetime issue - converting to utc

My database value is this
2020-03-08 20:44:00
But in javascript. It display
Mon Mar 09 2020 09:44:00 GMT+0800 (Singapore Standard Time)
Want i want to display on UI
2020-03-08 20:44:00
or
2020-03-08
Is there a way to remove the timezone and get only the actual value from the database.
toISOString is not a proper way to get date into DateTime. please follow the below method to get a date from DateTime.
var date = new Date("2020-03-08 20:44:00");
var year = date.getFullYear();
var month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
var newDate = year + '-' + month + '-' + day;
console.log("Date plush time - "+date);
console.log("Only Date - "+newDate);
You're using the silently using Date object's .toString() method which converts the UTC date (that your database is storing) into a time in the current time zone.
If date is the variable that you get from your database, then you can format it like you want it like this:
let dateString = date.toISOString().replace('T', ' ').replace(/\..+/, '')
This will take your date, convert it into an ISO string (in the form 2020-01-10T03:09:24.551Z) and replace the T with a space and everything after the decimal with nothing.
Try this.
let d = new Date('2020-03-08 20:44:00');
console.log(`${d.getFullYear()}-${d.getMonth() < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1}-${d.getDate() < 10 ? '0' + (d.getDate()): d.getDate()}`);
You can take each part of the date and construct your own format
example:
let formatted_date = my_date.getFullYear() + "-" + (my_date.getMonth() + 1) + "-" + my_date.getDate()
in this example: my_date hold the date you want to display.
If you're able to use a library, use moment.js
https://momentjs.com/docs/#/displaying/
moment("2020-03-08 20:44:00").format("YYYY-MM-DD");
or
moment(new Date("2020-03-08 20:44:00")).format("YYYY-MM-DD");
It can even change the time to utc
https://momentjs.com/guides/#/parsing/local-utc-zone/
moment.utc("2020-03-08 20:44:00").format("YYYY-MM-DD");
hope this helps :)
Subtract your timezone offset milliseconds.
var dt = new Date('2020-03-08 20:44:00');
dt = new Date(dt.getTime()-dt.getTimezoneOffset()*60000);
console.log(dt.toUTCString());
var mo = dt.getUTCMonth()+1, d = dt.getUTCDate(), h = dt.getUTCHours();
var m = dt.getUTCMinutes(), s = dt.getUTCSeconds();
if(mo < 10)mo = '0'+mo;
if(d < 10)d = '0'+d;
if(h < 10)h = '0'+h;
if(m < 10)m = '0'+m;
if(s < 10)s = '0'+s;
console.log(dt.getUTCFullYear()+'-'+mo+'-'+d+' '+h+':'+m+':'+s);

HTML5 get date string convert to date object

I try to use html5 type="date" and get the string and convert it to Date() in JS.
var dateString = $(this).prev().val();
var date = new Date(dateString);
var day = date.getDay();
var month = date.getMonth();
var year = date.getYear();
finalDate = day + "/" + month + "/" + year;
alert(finalDate);
But the result I got is different than what I've set, I have no idea what's wrong here :
I expect to get 18/05/1991
My demo is here http://jsfiddle.net/yL1q3ygf/
getMonth() returns a number between 0 and 11. You want to use getMonth()+1.
getDay() returns the day of the week, you want to use getDate() instead.
use getUTCDate(); before making it as an object (date).
var d = new Date(dateString);
var n = d.getUTCDate();
then use n in your code. it will work
$(function(){
$('button').click(function(){
var dateString = $(this).prev().val();
var date = new Date(dateString);
var day = date.getDate(); //day is for day of week. use date
var month = date.getMonth() +1; // months are zero based
var year = date.getFullYear(); //use full year for 4 digit year
finalDate = day + "/" + month + "/" + year;
alert(finalDate);
});
});
I updated your jsfiddle script
http://jsfiddle.net/yL1q3ygf/5/

JavaScript date: How to add a year to a string that contains mm/dd?

I have an string that contains month/date and I need to insert the year. The string looks like:
Last Mark:: 2/27 6:57 PM
I want to convert the string to something like:
Last Mark:: 2010/02/27 18:57
In this case, there will not be any entries more than a year old. For example, if the date were 10/12 it can be assumed that the year is 2009.
What is the best method for this?
Following from Adam's suggestion:
function convertDate(yourDate) {
var today = new Date();
var newDate = new Date(today.getFullYear() + '/' + yourDate);
// If newDate is in the future, subtract 1 from year
if (newDate > today)
newDate.setFullYear(newDate.getFullYear() - 1);
// Get the month and day value from newDate
var month = newDate.getMonth() + 1;
var day = newDate.getDate();
// Add the 0 padding to months and days smaller than 10
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
// Return a string in YYYY/MM/DD HH:MM format
return newDate.getFullYear() + '/' +
month + '/' +
day + ' ' +
newDate.getHours() + ':' +
newDate.getMinutes();
}
convertDate('2/27 6:57 PM'); // Returns: "2010/02/27 18:57"
convertDate('3/27 6:57 PM'); // Returns: "2009/03/27 18:57"
the code for adding THIS year is simple
var d = Date();
var withYear = d.getFullYear() + yourDate;
however, the logic behind considerating if it should be this year or last year could be harder to do
I would think this way: get today's date. If the date is higher than today's, it's last year, so add d.getFullYear()-1, otherwise add d.getFullYear()
This returns the current year:
var d = new Date();
var year = d.getFullYear();
To figure whether its this year or not you could just compare the day and month with the current day and month, and if necessary, subtract 1 from the year.
To get the day and month from the Date object:
d.getMonth(); // warning this is 0-indexed (0-11)
d.getDate(); // this is 1-indexed (1-31)

Categories

Resources