Javascript date format issue to string - javascript

When I convert from date to String, my date is changing. What is the my fault?
Date is returned me:
Date 2016-10-31T22:00:00.000Z
And when I convert to String I get:
Thu Dec 01 2016 00:00:00 GMT+0200
My code:
date = new Date("2016 11 31");
StringDate = date.toString();
console.log(StringDate);
console.log(date);

You're after UTC time, which can be printed with Date.toUTCString():
var date = new Date("2016 11 31");
var stringDate = date.toUTCString(); // See this line
console.log(stringDate);
console.log(date);

Actually your input is wrong.There is no such date 2016-11-31. Thats why it shows Dec 01 2016.
Try this:
date=new Date("2016 10 31"); //november consist 30 days only
StringDate=date.toString();
console.log(StringDate);
console.log(date);

Related

How to change ISO date to Standard JS Date?

I am trying to change an ISO date to a Standard JS Date format. The JS format I am referring to is:
Mon `Jul 20 2020 14:29:52 GMT-0500 (Central Daylight Time)`
What is the best way to go about doing this? Thanks!
const ISO_DATE = '2020-07-14T23:02:27.713Z';
function formatDate(dateStr) {
const date = new Date(dateStr);
return date.toString();
};
console.log(formatDate(ISO_DATE));
One way is:
let isoDate = "2020-07-20T14:29:52Z";
var myDate = new Date(isoDate);
console.log(myDate.toString()); // Mon Jul 20 2020 17:29:52 GMT+0300 ( (your time zone)
console.log("Back to ISO Date: ", myDate .toISOString());
If you want to convert it back to ISO Date use:
console.log(myDate.toISOString());

How to convert a Date object to output only hh:mm am/pm

I am attempting to convert the following into a 12 hour am/pm format.
Currently I am recieving the Day, Month, Year and timezone.
Fixed by adding .toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.)/, "$1$3")*
<div id="time1"></div>
<div id="time2"></div>
var date = new Date('08/16/2019 12:00:00 PM UTC').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3")
document.getElementById("time1").innerHTML = date;
var date = new Date('08/16/2019 6:00:00 am UTC').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3")
document.getElementById("time2").innerHTML = date;
Basically what you have to do is use the Date() default javascript function and make sure you append the UTC timezone:
var date = new Date('08/16/2019 7:00:00 PM UTC')
date.toString=() //will then print out the timezone adjusted time
"Fri Aug 16 2019 22:00:00 GMT+0300 (Eastern European Summer Time)"
There are many built in javascript methods to handle converting date objects. This example will look to the browser to determine date format and time.
let time = Date.now();
time.toLocaleDateString();

momentJS convert possibility day into Date() js format

I am trying to convert a date in format momentjs into a date from javascript native new Date().
The problem is that if I have moment(myDay).toDate(); it converts to the current date, and I want the date from myDay.
myDay looks like: "YYYY-MM-DD" => 2017-11-24 and I would like to have it with the format: Fri Nov 24 2017 20:17:11 GMT+0100 (Hora estándar romance) but I get Thu Nov 16 2017 etc...
It is possible to convert it like that way?
Don't need moment:
let [yr, mn, day] = myDay.split('-').map(Number);
// note that JS months are 0-11 not 1-12
let datestr = new Date(yr, mn - 1, dy).toString();
console.log(datestr); // "Fri Nov 24 2017 00:00:00 GMT-0500 (EST)"
you want something like this:
moment(myDay, "YYYY-MM-DD").toString();
moment().toString() Returns an english string in a similar format to JS Date's .toString().
moment().toString() // "Sat Apr 30 2016 16:59:46 GMT-0500"

Convert JavaScript new Date() to php DateTime()

I have 2 fields in HTML:
<input id="datum" type="date">
<input id="uhrzeit" type="time">
JavaScript:
var datumUhrzeit = new Date($("#datum").val()+","+$("#uhrzeit").val());
console.log(datumuhrzeit);
"Tue Aug 18 2015 16:45:00 GMT+0200 (Mitteleuropäische Sommerzeit)"
How can I convert "Tue Aug 18 2015 16:45:00 GMT+0200 (Mitteleuropäische Sommerzeit)" in PHP to a DateTime, so that I can save it to postgresql?
You can get unix timestamp from Date object as follows (see Date.prototype.getTime)
var timestamp = '#' + Math.round(datumUhrzeit.getTime()/1000);
Then when sent on server simply create new datetime object
$datumUhrzeit = new DateTime($timestamp);
If you can't use javascript to create timestamp and you get the the data from form directly you can do something like this, remember to set the timezone:
$datum = $_GET['datum'];
$uhrzeit = $_GET['uhrzeit'];
$datumUhrzeit = DateTime::createFromFormat('Y-m-d H:i:s', $datum . ' ' . $uhrzeit, new DateTimeZone('Europe/Berlin'));
Now as you have saved your date to the database and retrieved it, you can send it back
print $datumUhrzeit->format('U'); // This will print the time as unix timestamp
After that you would create your javascript date object with just the timestamp
var datumUhrzeit = new Date(timestamp * 1000); // timestamp from above
If you for some reason don't want to use unix timestamp you can print it in desired format with format method. Remember to set the timezone beforehand
$datumUhrzeit->setTimezone(new DateTimeZone('Europe/Berlin'));
print $datumUhrzeit->format('Y-m-d H:i:s');
Because javascript doesn't work well with timezones I would advocate you to use unix timestamps when you can. This way you have less problems with timezones.
You can use this javascript function to convert the dateObject or date string to your desired format:
/**
* Formats a dateObject or date string to Y-m-d date
* Example: Converts dateObject or date string Sat Aug 19 2017 00:00:00 GMT+0530 (India Standard Time) TO 2017-08-19
*/
function format_date( date )
{
if (typeof date == "string")
{
date = new Date(date);
}
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;
return year+'-'+month+'-'+day;
}
var dateString = 'Tue Aug 18 2015 16:45:00 GMT+0200 (Mitteleuropäische Sommerzeit)';
var formattedDate = format_date(dateString);//returned formatted date is 2015-08-18
Then you can pass this formatted date to your PHP code where you can use function strtotime to convert this date to your desired format. For ex:
$myFormattedDate = date('d-m-Y', strtotime($_REQUEST['formattedDate']));
You can do something like
$datumUhrzeit = 'Tue Aug 18 2015 16:45:00 GMT+0200 (Mitteleuropäische Sommerzeit)';
$datumUhrzeit = substr($datumUhrzeit, 0, strpos($datumUhrzeit, '('));
$resultDate = date('Y-m-d h:i:s', strtotime($datumUhrzeit));
echo $resultDate;
try this one
function myFunction() {
var content = document.getElementById("datum").value+","+document.getElementById("uhrzeit").value;
console.log(content);
}

Get exact day from date string in Javascript

I have checked this SO post: Where can I find documentation on formatting a date in JavaScript?
Also I have looked into http://home.clara.net/shotover/datetest.htm
My string is: Mon Jun 24 2013 05:30:00 GMT+0530 (India Standard Time)
And I want to convert it to dd-mm-yyyy format.
I tried using:
var dateString = 'Mon Jun 24 2013 05:30:00 GMT+0530 (India Standard Time)';
var myDate = new Date(dateString);
var final_date = myDate.getDay()+"-"+(myDate.getMonth()+1)+"-"+myDate.getFullYear();
But it gives me the result as: 1-6-2013
The getDay() value is the index of day in a week.
For Instance,
If my dateString is Thu Jun 20 2013 05:30:00 GMT+0530 (India Standard Time)
it gives output as 4-6-2013
How can I get the proper value of Day?
P.S: I tried using .toLocaleString() and creating new date object from it. But it gives the same result.
To get the day of the month use getDate():
var final_date = myDate.getDate()+"-"+(myDate.getMonth()+1)+"-"+myDate.getFullYear();
W3 schools suggests just building your days of the week array and using it:
var d=new Date();
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
var n = weekday[d.getDay()];
Not super elegant, but usable.
var dateString = 'Mon Jun 24 2013 05:30:00 GMT+0530 (India Standard Time)';
var myDate = new Date(dateString);
var final_date = myDate.getDate()+"-"+(myDate.getMonth()+1)+"-"+myDate.getFullYear();
Replace getDay() with getDate().
The above will return the local date for each date part, use the UTC variants if you need the universal time.
I think you will have to take an Array of the days & utilize it using the received index from the getDay() method.
To get required format with given date will achieve with moment.js.
a one liner solution is
import moment from "moment";
const date = new Date();
const finalDate = moment(date).format("DD-MM-YYYY")

Categories

Resources