Java 如何将长转换/转换为字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1854924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:18:33  来源:igfitidea点击:

How to convert / cast long to String?

javastringtype-conversionlong-integer

提问by user225714

I just created sample BB app, which can allow to choose the date.

我刚刚创建了示例 BB 应用程序,它可以允许选择日期。

DateField curDateFld = new DateField("Choose Date: ",
  System.currentTimeMillis(), DateField.DATE | DateField.FIELD_LEFT);

After choosing the date, I need to convert that long value to String, so that I can easily store the date value somewhere in database. I am new to Java and Blackberry development.

选择日期后,我需要将该长值转换为字符串,以便我可以轻松地将日期值存储在数据库中的某处。我是 Java 和 Blackberry 开发的新手。

long date = curDateFld.getDate();

How should I convert this long value to String? Also I want to convert back to long from String. I think for that I can use long l = Long.parseLong("myStr");?

我应该如何将这个长值转换为字符串?另外我想从String转换回long。我认为我可以使用long l = Long.parseLong("myStr");

回答by Gregory Pakosz

See the reference documentation for the String class: String s = String.valueOf(date);

请参阅String 类参考文档String s = String.valueOf(date);

If your Long might be null and you don't want to get a 4-letter "null"string, you might use Objects.toString, like: String s = Objects.toString(date, null);

如果您的 Long 可能为 null 并且您不想获得 4 个字母的"null"字符串,则可以使用Objects.toString,例如:String s = Objects.toString(date, null);



EDIT:

编辑:

You reverse it using Long l = Long.valueOf(s);but in this direction you need to catch NumberFormatException

您使用反转它Long l = Long.valueOf(s);但在这个方向上您需要抓住NumberFormatException

回答by MR.M

very simple, just concatenate the long to a string.

非常简单,只需将 long 连接到一个字符串。

long date = curDateFld.getDate(); 
String str = ""+date;

回答by Fisu

String strLong = Long.toString(longNumber);

Simple and works fine :-)

简单且工作正常:-)

回答by iKushal

1.

1.

long date = curDateFld.getDate();
//convert long to string
String str = String.valueOf(date);

//convert string to long
date = Long.valueOf(str);

2.

2.

 //convert long to string just concat long with empty string
 String str = ""+date;
//convert string to long

date = Long.valueOf(str);

回答by MBR

String logStringVal= date+"";

Can convert the long into string object, cool shortcut for converting into string...but use of String.valueOf(date);is advisable

可以将 long 转换为字符串对象,很酷的转换为字符串的快捷方式...但String.valueOf(date);建议使用

回答by CONvid19

Long.toString()

Long.toString()

The following should work:

以下应该工作:

long myLong = 1234567890123L;
String myString = Long.toString(myLong);

回答by Nathan Meyer

String longString = new String(""+long);

or

或者

String longString = new Long(datelong).toString();