Convert today's date to given format - javascript

I am trying to convert today's date in particular format and this date format can be anything like - dd/mm/yyyy or yyyy.mm.dd and so on
var date = new Date();
var todaysDate = date.toString('mm/dd/yyyy');
However, this code is not working.
Is there any other way to get it done.
I am looking for a common way where today's date can be converted to any given format

You could use Moment JS -- my go to JS date library -- to do something like
Moment (new Date ()).format("MM/DD/YYYY")
Or, if you know the form of the datetime format of the input string
Moment(string, "DD/MM/yyyy").format("MM/DD/YYYY")
MomentJS has other advantages too like adding time or dates or diffing two datetimes.
Alternatively, you could use Date Class functions to get parts of a Datetime and custom print or format them.
See StackOverflow format JS Date

I think, it is useful for u.
var currentDt = new Date();
var mm = currentDt.getMonth() + 1;
var dd = currentDt.getDate();
var yyyy = currentDt.getFullYear();
var date = mm + '/' + dd + '/' + yyyy;
alert(date);

Related

JavaScript input date convertion

Is there any way to convert any date string (not necessarily current date) (could be any format) to specific date format in Javascript. Like converting "MM-DD-YYYY" or "ddMMYYYY" to "DD-MMM-YYYY"?
I know that from current date as var date = new Date(), we can get time and hours but what to do in case of existing date string like "31/01/1999" to "31-JAN-1999".
Given the input date string can be of any format.
This is a common problem.
You should be able to do it with moment.js.
Ex.
moment("31/01/1999").formatWithJDF("dd - MM - yyyy");
Have a look here, https://momentjs.com/docs/ for more details.
Using DateFormatter.js
var date = new Date('2020-03-25 10:30:25');
var formatter = new DateFormatter();
displayFormat = 'D M d Y h:i:s';
var dateString = formatter.formatDate(date, displayFormat); // Wed Mar 25 2020 10:30:25
This can be done by first checking the input date format with the arrays or Map of regex provided, then need to convert that format to JS accepted format ISO format.
Once converted to ISO format this date now can be converted to any form with logic written for it in separate functions.

moment-timezone parsing the given time zone

I have an issue when parsing the Date object using the moment-timezone
The problem
I am creating a nodejs app that should check the new Date() object with arbitrary time from database (and act accordingly). The time, and the timezone are persisted in database.
In example
time | timezone
11:00| US/Eastern
When a REST call comes, I have to take new Date() object and to transform it to given timezone and see whether the current time is later than 9am. But servers timezone and persisted timezone are not the same.
The issue
I create todays date string like this
function getTodaysDate() {
var today = new Date(),
dd = today.getDate(),
mm = today.getMonth()+1,
yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
return yyyy +'-' + mm + '-' + dd;
}
And trying to create Timestamp object with moment-timezone
startTime = moment.tz(new Date(getTodaysDate() + ' ' + '11:00'), 'US/Eastern');
But the framework correctly takes the date and transforms it to US/Eastern time zone.
So when I print startTime.format();
I get
2016-08-01T07:00:00-04:00
And I would like
2016-08-01T11:00:00-04:00
So is there a way using moment-timezone package to set the Date and time and to just treat them as given timezone?
So the problem was that
startTime = moment.tz('here the date goes', 'US/Eastern');
Was either expecting ISO format or manually formatted (syntax of this was not known to me), or the Date() object. I first tried with this
2016-08-01 11:00
Moment library complained (I will post the full error message when I come to office).
Solution
Add T.
startTime = moment.tz('2016-08-01T11:00', 'US/Eastern');
I hate timedate libraries and how we track of time.
You don't need any of the Date object manipulation. In theory, you should just be able to do:
var zone = 'US/Eastern'
var time = '11:00'
var result = moment.tz(time, 'HH:mm', zone).format();
However, there's a known bug with this that uses the UTC current date instead of the time zone's current date. Until it's fixed, you have to do this instead:
var zone = 'US/Eastern'
var time = '11:00'
var s = moment.tz(zone).format('YYYY-MM-DD') + ' ' + time;
var m = moment.tz(s, zone);
var result = m.format();
(this assumes your input time value is in HH:mm format)

Converting Javascript String to Datetime

I have a text box that is populated from a datepicker in Javascript. The date is stored as 30-Jan-2013. I want to convert this to a date so I can use it in other calculations.
I have tried
var date1 = new Date(document.getElementById('textbox').value)
but this returns Nan
if I drop the new Date part e.g.
var date1 = (document.getElementById('textbox').value
I get the date 30-Jan-2013 I just don't seem to be able to convert this?
Looks like Date.parse is not going to work because the format the datepicker is returning.
You might want to look at the following thread for parsing solutions or change your format that the datepicker outputs to one of the supported formats.
How can I convert string to datetime with format specification in JavaScript?
http://blog.dygraphs.com/2012/03/javascript-and-dates-what-mess.html
Useful parse info:
http://msdn.microsoft.com/en-us/library/ie/ff743760(v=vs.94).aspx
I'd like to recommend you a simple, easy to use and fast library [moment.js][1]
moment("30-Jan-2013").format('MMMM Do YYYY, h:mm:ss a');
will return "January 30th 2013, 12:00:00 am"
Hope this will work for your problem
var date= document.getElementById('textbox').value.split("-");;
var date1 = new Date(date[2] + " " + date[1] + " " + date[0]);
date1 .toLocaleDateString("en-GB");

how to compare date which is given by user to date in javascript..?

In my web-site I am getting a date from user which in format like "dd-mm-yyyy",now I want to get the date which is 7-day before of that user's date.
I am able to get the current date in format "dd-mm-yyyy" but how would I know the date which is one week before user's date in javascript?
If you already have a Date object, use yourDate.setDate(yourDate.getDate() - 7 );
Try this--
var MyDate = new Date('11/30/2012'); //date format in mm/dd/yyyy
MyDate.setDate(MyDate.getDate() -7)
var newDate = MyDate.getMonth()+1 + '/' + MyDate.getDate() + '/' + MyDate.getFullYear()
alert(newDate);
Note- subtracting seven days to a date shifts the month or year and the changes are handled automatically by the Date object.
Why don't you use datejs, it's the best date related js library I have seen. Chcek the documentation here.
http://code.google.com/p/datejs/wiki/APIDocumentation
Search for add method
Set Dates
We can easily manipulate the date by using the methods available for the Date object.
In the example below we set a Date object to a specific date (14th January 2010):
var myDate=new Date();
myDate.setFullYear(2010,0,14);
And in the following example we set a Date object to be 7 days in past:
var myDate=new Date(); //or users date
// myDate will be users current date
myDate.setDate(myDate.getDate()-7);
//now substract 7 days to get the date u want.
Follow the following link
http://www.w3schools.com/js/js_obj_date.asp
Or follow this
http://www.techrepublic.com/article/manipulate-time-and-date-values-with-javascripts-date-object/6076869
You can convert a date string in the format dd-mm-yyyy to a date object using:
function toDate(d) {
d = d.split('-');
return new Date(d[2], --d[1], d[0]);
}
Then use Osiris' answer to add or subtract 7 days.

How to format JSON date?

so, i need format JSON date from this format
"9/30/2010 12:00:00 AM", it is MM/DD/YYYY HH:MM:SS to format like this : DD/MM/YYYY, so i dont need info about hours, min and sec, and i need replace months and days from json, i tried some different ways but it always failed
i need do this using jQuery
also i didnt find any answer to formating this date type, all i found was formating date like this :/Date(1224043200000)/
so anyone have idea?
you can create a Date Object from a string like so:
var myDate = new Date(dateString);
then you can manipulate it anyway you want, one way to get your desired output is:
var output = myDate.getDate() + "\\" + (myDate.getMonth()+1) + "\\" + myDate.getFullYear();
you can find more at this elated.com article "working with dates"
Unfortunately your "from" dateformat is not the one which is implementation-independent in JavaScript. And all the other formats depends on the implementation, which means even if this format would be understood by most of the implementation I/you can't be sure for example how the DD and MM order would be parsed (I am almost sure it would be local regional settings dependent). So I would recommend to use a 3rd party (or your hand written) date parser to get a Date object out of your input string. One such parser you can find here:
http://www.mattkruse.com/javascript/date/
Because your question is not 100% clear for me, it's possible that you have your date in the format of /Date(number)/ which suggests that you are calling an ASP.Net service from your jQuery code. In this case during the JSON parse you can convert it to a Date object:
data = JSON.parse(data, function (key, value) {
// parsing MS serialized DateTime strings
if (key == '[NAME_OF_DATE_PROPERTY_IN_THE_JSON_STRING]') {
return new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
// maybe new Date(parseInt(value.substr(6))) also works and it's simpler
}
return value;
});
The code below solved my problem:
var date = new Date(parseInt(d.data[i].dtOrderDate.replace("/Date(", "").replace(")/", ""), 10));
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
Try something like this :
var date = new Date(parseInt(jsonDate.substr(6)));
where jsonDate is variable that stores your date

Categories