Make JavaScript Date function accept string or date object - javascript

I have this simple JavaScript function below that converts a JavaScript Date into a more readable format.
Right now you have to pass in a valid Date object but I would like to modify it so that it will accept a Date object or a string with a date value and return a formatted date regardless of which version is passed into it.
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return date.getMonth()+1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
Usage:
var d = new Date(date_string);
var e = formatDate(d);
Converts this 2015-09-16 03:18:12 into 9/16/2015 3:18 pm
I want to be able to pass in a Date object...
var dateObject = new Date(date_string);
var e = formatDate(dateObject);
or a Date string...
var dateString = `2015-09-16 03:18:12`;
var e = formatDate(dateString);

The way to do this is to do type checking in the function via typeof.
function formatDate(date) {
if(typeof date === "string") {
// parse the date string into a Date object
}
// now date is already a Date object, or it has been parsed
var hours = date.getHours();
...
Actually parsing the Date string is outside the scope of the question.

You can check the type of variable before deciding which way to go:
function formatDate(date) {
if(typeof(date) == "string") {
var date_string = date;
date = new Date(date_string);
}
// Then just keep going!
}

Related

Convert date object in dd/mm/yyyy hh:mm:ss format [duplicate]

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 5 years ago.
I have a datetime object and its value is as follows
2017-03-16T17:46:53.677
Can someone please let me know how to convert this to dd/mm/yyyy hh:mm:ss format
I googled a lott and could not find format conversion for this particular input.
You can fully format the string as mentioned in other posts. But I think your better off using the locale functions in the date object?
var d = new Date("2017-03-16T17:46:53.677");
console.log( d.toLocaleString() );
edit :
ISO 8601 ( the format you are constructing with ) states the time zone is appended at the end with a [{+|-}hh][:mm] at the end of the string.
so you could do this :
var tzOffset = "+07:00"
var d = new Date("2017-03-16T17:46:53.677"+ tzOffset);
console.log(d.toLocaleString());
var d = new Date("2017-03-16T17:46:53.677"); // assumes local time.
console.log(d.toLocaleString());
var d = new Date("2017-03-16T17:46:53.677Z"); // UTC time
console.log(d.toLocaleString());
edit :
Just so you know the locale function displays the date and time in the manner of the users language and location. European date is dd/mm/yyyy and US is mm/dd/yyyy.
var d = new Date("2017-03-16T17:46:53.677");
console.log(d.toLocaleString("en-US"));
console.log(d.toLocaleString("en-GB"));
Here we go:
var today = new Date();
var day = today.getDate() + "";
var month = (today.getMonth() + 1) + "";
var year = today.getFullYear() + "";
var hour = today.getHours() + "";
var minutes = today.getMinutes() + "";
var seconds = today.getSeconds() + "";
day = checkZero(day);
month = checkZero(month);
year = checkZero(year);
hour = checkZero(hour);
minutes = checkZero(minutes);
seconds = checkZero(seconds);
console.log(day + "/" + month + "/" + year + " " + hour + ":" + minutes + ":" + seconds);
function checkZero(data){
if(data.length == 1){
data = "0" + data;
}
return data;
}

Remove trailing zeroes in date in JavaScript

I am using the current format in order to product a JavaScript date:
var date = visitdate;
var newdate = date.split("/").reverse().join("-");
I would expect this to return 1900-01-01 for example, however what this actually returns is 1900-01-0100.
Iv'e tried using slice in order to trim this off but this just ends up slicing off the day instead and still adds the zeros. There seems to be no way of getting rid of them. Is there anyway to remove them?
You may write a function like below and whatever format needed you can change
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
hours = hours < 10 ? '0'+hours : hours;
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
var Month = date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1;
var Date = date.getDate() < 10 ? '0'+date.getDate() : date.getDate();
var strDate = Month + "/" + Date + "/" + date.getFullYear();
return strDate + " " + strTime;
}
Or in your case if you dont want time just remove strTime from return of function
Assuming the input is "01/01/1900 00:00" - add a .split(" ") in between like this:
"01/01/1900 00:00".split(" ")[0].split("/").reverse().join("-");
Or just skip the reverse() if your input is like you said "1900-01-01":
"1900/01/01 00:00".split(" ")[0].split("/").join("-");
You could also extract the information from your date string by using a regex like this:
var d = '1990/01/01 00:00';
var matches = d.match(/^(\d+)\/(\d+)\/(\d+) (\d+):(\d+)$/);
if(matches){
var year = matches[1]
, month = matches[2]
, day = matches[3]
, hour = matches[4]
, minutes = matches[5];
console.log(year+'-'+month+'-'+day);
}

Date format conversion in node js

I am using a form ,from which the user can select the datetime from datetime picker in dd-mm-yyyy hh:mm:ss format. Now I want to convert the format to yyyy-mm-dd hh:mm:ss format to store in mysql table.
I tried with moment js like this
console.log(moment(status.date).format('MM/DD/YYYY'));
where status.date I will post from a form where the user selects datetime from datetimepicker.
Please help
You can do like this instead of having some modules.
var fd = status.date;
var fromDate = fd.split(" ");
console.log(formatDate(fromDate[0],fromDate[1] + " " + fromDate[2]));//
and add these functions there.
function formatDate(date, time2) {
var from = date.split("-");
var f = from[2] + "-" + from[1] + "-" + from[0];
var time1 = time(time2);
return f + " " + time1;
}
function time(time) {
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if ((AMPM == "PM" || AMPM == "pm") && hours < 12)
hours = hours + 12;
if ((AMPM == "AM" || AMPM == "am") && hours == 12)
hours = hours - 12;
var sHours = hours.toString();
if (hours < 10)
sHours = "0" + sHours;
if (minutes < 10)
sMinutes = "0" + sMinutes;
return (sHours + ":" + sMinutes);
}
Convert it to ISOString first and then eliminate unwanted things by replace method.
var date = new Date();
date.toISOString().replace(/T/, " ").replace(/\..+/,'')
source: chbrown's answer
Building on top of Prateek Jain's ISOString method, we can use toLocaleString to obtain the local time in ISO format.
One needs to shop around the base format provided by toLocaleString according to different regions. The format closest to ISO is en-CA (refer to this answer for all the region-based format). We then use the option {hour12: false} to convert to 24-hour notation.
const d = new Date();
d.toLocaleString('en-CA', {hour12: false}).replace(/, /, ' ');

Javascript: Formatting datetime yields NaN results

I am trying to format a mysql datetime object in Javascript, but I only get NaN results.
The value from the database is for example this datetime object:
2015-08-27 21:36:03
In my JS I try to convert this object as follows:
var formattedDate = new Date(datetimeObj);
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes;
return date.getMonth()+1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
How come that I when printing the variable, I get NaN/NaN/NaN 12:NaN?
Some browsers will not parse the string "2015-08-27 21:36:03" as a valid date. For best results, use a standard ISO date string, as in
2015-08-27T21:36:03Z
Try this:
<script>
var formattedDate = new Date("2015-08-27 21:36:03");
console.log(formatDate(formattedDate));
function formatDate(date)
{
var hours = date.getHours();
var minutes = date.getMinutes();
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = hours + ':' + minutes;
return date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
</script>
Its the same code, just passed the input in your function..
Here you can find answer on your quetions, it something like this with RegEx
var dateString = "2010-08-09 01:02:03";
var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
var dateArray = reggie.exec(dateString);
var dateObject = new Date(
(+dateArray[1]),
(+dateArray[2])-1, // Careful, month starts at 0!
(+dateArray[3]),
(+dateArray[4]),
(+dateArray[5]),
(+dateArray[6])
);

convert unix time to date object

I have a unix time and need to get a Date object from it.
This code just transform the timestamp to human readable way:
var date = new Date(unix_timestamp*1000);
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
var formattedTime = hours + ':' + minutes + ':' + seconds;
As a result I get 13:44:6, for instance
but how I can create a Date object with time and date from it?
You can take a look at date.js
http://www.datejs.com/
var datestr = "13:44:06";
var date = Date.parse(datestr,"hh:mm:ss");
alert(date);
This alerts a date string set to today's date, but with the time in datestr.
NOTE For this to work, I needed to zero-pad the seconds.
EDIT
The link for date.js format specifiers is a bit buried, so here's that link if you need it:
http://code.google.com/p/datejs/wiki/FormatSpecifiers
I wrote a prototype function for Date object to convert unix timestamp to YYYYMMDD.
You can edit it as you like
var bd = new Date(unix_timestamp * 1000);
bd = bd.toYYYYMMDD();
// 1970-01-01
if ( !Date.prototype.toYYYYMMDD ) {
( function() {
function pad(number) {
var r = String(number);
if ( r.length === 1 ) {
r = '0' + r;
}
return r;
}
Date.prototype.toYYYYMMDD = function() {
if(!this.getUTCDate() || this.getUTCDate() === 'NaN')
return '1970-01-01';
return this.getUTCFullYear()
+ '-' + pad( this.getUTCMonth() + 1 )
+ '-' + pad( this.getUTCDate() );
};
}() );
};

Categories